我尝试使用裁剪框UIImage
裁剪UIView
,用户可以在图片视图中的任意位置拖动以进行裁剪。我用来计算裁剪矩形的逻辑如下:
extension UIImageView {
public func computeCropRect(for sourceFrame : CGRect) -> CGRect {
let widthScale = bounds.size.width / image!.size.width
let heightScale = bounds.size.height / image!.size.height
var x : CGFloat = 0
var y : CGFloat = 0
var width : CGFloat = 0
var height : CGFloat = 0
var offSet : CGFloat = 0
if widthScale < heightScale {
offSet = (bounds.size.height - (image!.size.height * widthScale))/2
x = sourceFrame.origin.x / widthScale
y = (sourceFrame.origin.y - offSet) / widthScale
width = sourceFrame.size.width / widthScale
height = sourceFrame.size.height / widthScale
} else {
offSet = (bounds.size.width - (image!.size.width * heightScale))/2
x = (sourceFrame.origin.x - offSet) / heightScale
y = sourceFrame.origin.y / heightScale
width = sourceFrame.size.width / heightScale
height = sourceFrame.size.height / heightScale
}
return CGRect(x: x, y: y, width: width, height: height)
}
}
裁剪框框架看起来像这样,可以通过拖动它定位在图像视图框架的任何位置:
这个裁剪代码工作正常,直到我将其与另一个功能结合起来我试图支持哪个能够让用户在UIImageView内使用他们的手指进行绘制。代码如下:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touchPoint = touches.first {
let currentPoint = touchPoint.location(in: self)
UIGraphicsBeginImageContextWithOptions(frame.size, false, UIScreen.main.scale)
if let context = UIGraphicsGetCurrentContext() {
image?.draw(in: imageEffectsService.computeAspectFitFrameFor(containerSize: frame.size, imageSize: image!.size), blendMode: .normal, alpha: CGFloat(imageOpacity))
drawLineAt(startPoint: lastTouchPoint, endPoint: currentPoint, currentContext: context, strokeColor: drawColor)
UIGraphicsEndImageContext()
}
}
}
private func drawLineAt(startPoint : CGPoint, endPoint : CGPoint, currentContext : CGContext, strokeColor : UIColor) {
currentContext.beginPath()
currentContext.setLineCap(CGLineCap.round)
currentContext.setLineWidth(brushSize)
currentContext.setStrokeColor(strokeColor.cgColor)
currentContext.move(to: startPoint)
currentContext.addLine(to: endPoint)
currentContext.strokePath()
image = UIGraphicsGetImageFromCurrentImageContext()
}
一旦我应用绘图,裁剪方法就会失去准确性,特别是因为这一行:
UIGraphicsBeginImageContextWithOptions(frame.size, false, UIScreen.main.scale)
如果我使用:
UIGraphicsBeginImageContext(frame.size)
我的裁剪代码将是准确的,但绘图保真度将看起来颗粒状和低质量,因为我不考虑视网膜屏幕设备。我的问题是如何修改我的裁剪功能以考虑UIScreen.main.scale
?