私は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()
}
}
}
}