swift将多个图像与一组图像进行比较

问题描述 投票:0回答:1

我有2个UIImageViews连接到我正在尝试比较的图像数组,一旦它们显示但似乎不起作用。我尝试使用imageArray [Image Literal]和imageArray [image1.png,image2.png,image3.png,image4.png,image5.png]我不知道我做错了什么。我不是在寻找代码,虽然它可能会有所帮助,但我正在寻找一个能引导我走向正确方向的人

@IBOutlet weak var 1ImageView: UIImageView!
@IBOutlet weak var 2ImageView: UIImageView!

    let imageArray = [image1.png, image2.png, image3.png, image4.png, image5.png]

func any() {
    if (1ImageView != nil) && (2ImageView != nil) && isEqual(image1.png) {
        print("match!")
    } else if ...// more if statements
    …last if statement} else {
        print(“no match!”)
}

@IBAction func buttonPressed(_ sender: IUButton) {
    any()
}

如果这是不可能的,有一种方法可以为数组内的每个图像分配一个标识符..对不起额外的问题。使用NSData比较2个图像有一个答案,但我不知道如何将它实现到数组。谢谢,抱歉,但新手问题。

ios swift uiimageview
1个回答
0
投票

尽管有文件说明,image.isEqual(image)似乎不可靠。如果您不需要进行像素完美比较,将图像转换为数据并进行比较就足够了。

    let image1 = UIImage(named: "image1.png")
    let image2 = UIImage(named: "image2.png")

    let imageData1 = image1?.pngData()
    let imageData2 = image2?.pngData()

    if imageData1 == imageData2 {
        print("images are the same")
    } else {
        print("images are different")
    }

在数组中寻找特定的图像可以建立在:

// array of images referencing image files within an Xcode project
// it's not the best idea to force unwrap those, but for the sake of simplicity
let imageArray = [UIImage(named: "image1.png")!,
                  UIImage(named: "image2.png")!,
                  UIImage(named: "image3.png")!,
                  UIImage(named: "image4.png")!,
                  UIImage(named: "image5.png")!]

func anySimilarImages() {
    // find first image which is the same as 1ImageView's
    let 1ImageViewImage: UIImage? = imageArray.first { (image) -> Bool in
        return  image.pngData() == 1ImageView.image?.pngData()
    }

    // find first image which is the same as 2ImageView's
    let 1ImageViewImage: UIImage? = imageArray.first { (image) -> Bool in
        return  image.pngData() == 2ImageView.image?.pngData()
    }

    if 1ImageViewImage != nil && 2ImageViewImage != nil {
        print("both images were found")
    }
    else if 1ImageViewImage != nil {
        print("first image was found")
    }
    else if 2ImageViewImage != nil {
        print("second image was found")
    }
    else {
        print("no image was found")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.