Drawing a rectangle on UIImageView using Core Graphics

大兔子大兔子 提交于 2019-12-08 03:31:25

问题


I want to let the User to draw a rectangle on UIImageView I added two variables for first an last touch locations I added this function:-

func draw(from: CGPoint, to: CGPoint) {
    UIGraphicsBeginImageContext(imageView.frame.size)
    context = UIGraphicsGetCurrentContext()
    context?.setStrokeColor(UIColor(red: 0, green: 0, blue: 0, alpha: 1.0).cgColor)
    context?.setLineWidth(5.0)
    let currentRect = CGRect(x: from.x,
                             y: from.y,
                             width: to.x - from.x,
                             height: to.y - from.y)
    context?.addRect(currentRect)
    context?.drawPath(using: .stroke)
    context?.strokePath()
    imageView.image?.draw(in: self.imageView.frame)
    imageView.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}

I add the method to (touchMoved) it draws many rectangles

I add the method to (touchEnded) it draws one, but it does not appear when the user move the touch

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        firstTouchLocation = touch.location(in: self.view)            
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        lastTouchLocation = touch.location(in: self.view)
        draw(from: firstTouchLocation, to: lastTouchLocation)
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        lastTouchLocation = touch.location(in: self.view)
        draw(from: firstTouchLocation, to: lastTouchLocation)
    }
}

I want to let the user extend the rectangle when touchMoved and draw when the touchEnded.


回答1:


You are replacing your image with a new image composed of the previous image plus a rectangle drawn over it. Rather than drawing the image from the image view, draw the original image.

Alternatively, you could render the the rectangle as a shape layer and just update that shape layer's path:

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    private let shapeLayer: CAShapeLayer = {
        let _shapeLayer = CAShapeLayer()
        _shapeLayer.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
        _shapeLayer.strokeColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor
        _shapeLayer.lineWidth = 3
        return _shapeLayer
    }()

    private var startPoint: CGPoint!

    override func viewDidLoad() {
        super.viewDidLoad()

        imageView.layer.addSublayer(shapeLayer)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        startPoint = touches.first?.location(in: imageView)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let startPoint = startPoint, let touch = touches.first else { return }

        let point: CGPoint

        if let predictedTouch = event?.predictedTouches(for: touch)?.last {
            point = predictedTouch.location(in: imageView)
        } else {
            point = touch.location(in: imageView)
        }

        updatePath(from: startPoint, to: point)
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let startPoint = startPoint, let touch = touches.first else { return }

        let point = touch.location(in: imageView)

        updatePath(from: startPoint, to: point)
        imageView.image = imageView.snapshot(afterScreenUpdates: true)
        shapeLayer.path = nil
    }

    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        shapeLayer.path = nil
    }

    private func updatePath(from startPoint: CGPoint, to point: CGPoint) {
        let size = CGSize(width: point.x - startPoint.x, height: point.y - startPoint.y)
        let rect = CGRect(origin: startPoint, size: size)
        shapeLayer.path = UIBezierPath(rect: rect).cgPath
    }

}

Where:

extension UIView {
    func snapshot(afterScreenUpdates: Bool = false) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
        drawHierarchy(in: bounds, afterScreenUpdates: afterScreenUpdates)
        let image = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}

This is not only simpler, but more efficient, too.

That yields:

By the way, I might suggest using predictive touches in touchesMoved. On a device (not the simulator) that can yield a slightly more responsive UI.



来源:https://stackoverflow.com/questions/45906289/drawing-a-rectangle-on-uiimageview-using-core-graphics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!