我试图在触摸位置复制背景图像的一部分,然后在与裁剪部分相同的位置添加 subview 。如果我做的正确,两张图片会排成一行,你无法分辨出那里有两个 UIImageView,但它最终看起来像下面的图片。为什么这没有对齐,为什么新图像放大了一点?
更新:我的 ImageView 与主视图大小相同,图像模式是 aspect fit,所以图像上方和下方的白色仍然是 imageview 的一部分。
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first!.locationInView(view)
let rect = CGRect(origin: touch, size: CGSize(width: 90, height: 90))
let imageRef = CGImageCreateWithImageInRect(mainImageView.image!.CGImage, rect)
if imageRef != nil {
let newImage = UIImage(CGImage: imageRef!)
let bgImage = UIImageView(image: newImage)
bgImage.center = touch
self.view.addSubview(bgImage)
self.view.bringSubviewToFront(bgImage)
}
}
接触前:
触后:
最佳答案
我终于明白了:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first!.locationInView(view)
UIGraphicsBeginImageContext(mainImageView.bounds.size)
UIApplication.sharedApplication().keyWindow!.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let crop = CGRectMake(touch.x - 45, touch.y - 45, 90, 90)
let imageRef = CGImageCreateWithImageInRect(screenshot.CGImage, crop)
if imageRef != nil {
let newImage: UIImage = UIImage(CGImage: imageRef!, scale: mainImageView.image!.scale, orientation: mainImageView.image!.imageOrientation)
let bgImage = UIImageView(image: newImage)
bgImage.center = touch
self.view.addSubview(bgImage)
self.view.bringSubviewToFront(bgImage)
}
}
}
}
关于ios - 无法快速使用 CGImageCreateWithImageInRect 裁剪触摸位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36366907/