我正在尝试在触摸位置复制背景图像的一部分,然后在裁剪部分的同一位置添加子视图。如果我正确地执行此操作,两个图像都会排成一行,您无法告诉两个UIImageViews,但最终看起来像下面的图片。为什么这不排队,为什么新图像放大了?
更新:我的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)
}
}
触摸前:
触摸后:
答案 0 :(得分:0)
我终于明白了:
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)
}
}
}
}