我試圖實現一個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()
}
}
}
}