我试图实现一个UIImageView
子类,它允许用户使用他们的手指在图像视图中绘制。我的UIImageView
的contentMode设置为Aspect Fill
。我注意到,当我的绘图代码执行并且从图形上下文中提取出结果图像时,它将以Scale to Fill
类型格式缩放,这不是我想要的。我想知道是否有人知道如何实现提取图像并保持图像的纵横比。UIGraphicsGetImageFromCurrentContext并保留长宽比
class DrawImageView : UIImageView {
var lastTouchPoint = CGPoint.zero
var isSwiping = false
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
isSwiping = false
if let touchPoint = touches.first {
lastTouchPoint = touchPoint.location(in: self)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
isSwiping = true
if let touchPoint = touches.first {
let currentPoint = touchPoint.location(in: self)
UIGraphicsBeginImageContext(frame.size)
image?.draw(in: CGRect(x:0, y:0, width:frame.size.width, height:frame.size.height))
if let context = UIGraphicsGetCurrentContext() {
context.move(to: lastTouchPoint)
context.addLine(to: currentPoint)
context.setLineCap(CGLineCap.round)
context.setLineWidth(9.0)
context.setStrokeColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0)
context.strokePath()
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
lastTouchPoint = currentPoint
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if(!isSwiping) {
UIGraphicsBeginImageContext(frame.size)
image?.draw(in: CGRect(x:0, y:0, width:frame.size.width, height:frame.size.height))
if let context = UIGraphicsGetCurrentContext() {
context.setLineCap(CGLineCap.round)
context.setLineWidth(9.0)
context.setStrokeColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0)
context.move(to: lastTouchPoint)
context.addLine(to: lastTouchPoint)
context.strokePath()
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
}
}