Tôi có UIImageView với UIImage. Tôi muốn gán một bản sao của những hình ảnh này cho hai biến. Dựa trên những gì người dùng đang thực hiện hình ảnh nên được thao tác. Vấn đề là, hình ảnh giống nhau trong mỗi biến. Tôi đoán, bởi vì chúng được chuyển qua tham chiếu.Làm cách nào để sao chép UIImage?
let image1 = imageView.image!
let image2 = imageView.image!
Làm cách nào để có hai bản sao riêng biệt của hình ảnh này?
Cảm ơn bạn!
Edit:
Những gì tôi muốn đạt được: Chỉ cần cắt một hình ảnh, giữ khác như bản gốc.
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)")
Đoạn mã trên bản in ra cửa sổ Console:
left image: <UIImage: 0x7fd020dca070>, {111, 167}
right image <UIImage: 0x7fd020dda430>, {111, 167}
left image: <UIImage: 0x7fd020df9ba0>, {110, 167}
right image <UIImage: 0x7fd020d45670>, {110, 167}
... và vân vân. Vì vậy, cả hai hình ảnh được một kích thước mới. Chỉ hình ảnh bên trái sẽ bị cắt.
http://stackoverflow.com/a/6770387/3324388 – Aggressor