我有一个带有UIImage的UIImageView。我想将这些图片的副本分配给两个变量。根据用户正在做的事情,应该操纵图像。问题是,每个变量的图像都是一样的。我想,因为它们是通过引用传递的。
let image1 = imageView.image!
let image2 = imageView.image!
如何获得此图像的两个单独副本?
谢谢!
修改
我想要实现的目标:只裁剪一张图像,保持另一张图像与原始图像一样。
let imageLeft = googleImageView.image!
let imageRef = CGImageCreateCopy(googleImageView.image!.CGImage)
let imageRight = UIImage(CGImage: imageRef!, scale: googleImageView.image!.scale, orientation: googleImageView.image!.imageOrientation)
if translation.x < 0 {
let scale = imageLeft.scale
let newRect = CGRectMake(0, 0, (imageLeft.size.width + translation.x) * scale, imageLeft.size.height * scale)
let imageRef = CGImageCreateWithImageInRect(imageLeft.CGImage, newRect)
if let croppedImage = imageRef {
googleImageView.image = UIImage(CGImage: croppedImage, scale: scale, orientation: imageLeft.imageOrientation)
}
}
print("left image: \(imageLeft) right image \(imageRight)")
上面的代码打印到控制台:
left image: <UIImage: 0x7fd020dca070>, {111, 167}
right image <UIImage: 0x7fd020dda430>, {111, 167}
left image: <UIImage: 0x7fd020df9ba0>, {110, 167}
right image <UIImage: 0x7fd020d45670>, {110, 167}
......等等。因此,两个图像都有了新的尺寸。只有左图像才会被裁剪。
答案 0 :(得分:10)
正如@Aggressor建议您可以通过以下方式从imageView复制图像:
let newCgIm = CGImageCreateCopy(imageView.image?.CGImage)
let newImage = UIImage(CGImage: newCgIm, scale: imageView.image!.scale, orientation: imageView.image!.imageOrientation)
答案 1 :(得分:6)
cgImage的新复制功能附带 Swift 3 ,并且与 Swift 4 兼容。所以你可以这样使用
guard let cgImage = imageView.image?.cgImage?.copy() else {
return
}
let newImage = UIImage(cgImage: cgImage,
scale: imageView.image!.scale,
orientation: imageView.image!.imageOrientation)