gpt4 book ai didi

ios - CGImageCreateWithImageInRect 切断

转载 作者:行者123 更新时间:2023-11-28 11:07:46 27 4
gpt4 key购买 nike

我在 Swift 中使用 CGImageCreateWithImageInRect 在触摸位置创建部分图像的副本。

我的代码运行良好,除非用户触摸屏幕边缘并且矩形大小落在 View 框架之外。它不是返回一个正方形,而是返回一个矩形(我假设)来切断 View 外的数量。形状的变化会偏离复制图像的位置,因此它不会与下方图像对齐。

如何保持正方形/大小并忽略边界,以便我的图像对齐?

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

let touch = touches.first!.locationInView(mainImageView?.superview)

UIGraphicsBeginImageContext(self.view.bounds.size)
UIApplication.sharedApplication().keyWindow!.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

let crop = CGRectMake(touch.x - CGFloat(brushWidth) / 2, touch.y - CGFloat(brushWidth) / 2, CGFloat(brushWidth), CGFloat(brushWidth))

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: processedImage)
bgImage.center = touch
self.view.addSubview(bgImage)

}
}
}

}

这是它工作的一个例子:

enter image description here

这是一个扭曲图像的例子,因为我触摸了边缘:

enter image description here

最佳答案

CGImageCreateWithImageInRect(screenshot.CGImage, crop) 确实返回了裁剪后的版本。以下是文档中的相关评论:

Quartz performs these tasks to create the subimage:

  • Adjusts the area specified by the rect parameter to integral bounds by calling the function CGRectIntegral.

  • Intersects the result with a rectangle whose origin is (0,0) and size is equal to the size of the image specified by the image parameter.

  • References the pixels within the resulting rectangle, treating the first pixel within the rectangle as the origin of the sub image.

解决此问题的一个简单方法是调整生成的 UIImageView 的位置,使其大小正确。下面是相关的计算:

let screenshotBounds = CGRectMake(0.0, 0.0, screenshot.size.width, screenshot.size.height)
let cropIntegral = CGRectIntegral(crop)
let cropIntersection = CGRectIntersection(cropIntegral, screenshotBounds)
bgImage.center = CGPoint(CGRectGetMidX(cropIntersection), CGRectGetMidY(cropIntersection))

cropIntersection 是我们提取图像的边界矩形(遵循文档中给出的前两个步骤)。因此,我们可以使用它来将 imageView 定位到原始图像中的相同位置。

关于ios - CGImageCreateWithImageInRect 切断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36705844/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com