Пытаюсь стереть uiimage с помощью swift

#swift #uiimage #crop #erase #uigraphicscontext

#swift #uiimage #обрезать #стереть #uigraphicscontext

Вопрос:

Я пытаюсь создать функцию ластика (и восстановить в будущем) для своего приложения, но сталкиваюсь с некоторыми проблемами. Я использую Swift 4.2, и это то, что я сделал до сих пор:

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first as UITouch?{
            let touchPoint = touch.location(in: self.lassoImageView)   lassoOffset!
            print("touch begin to : (touchPoint)")
            eraserStartPoint = touchPoint   
        }
    }
  
 override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first as UITouch?{
            let touchPoint = touch.location(in: self.lassoImageView)   lassoOffset!
            print("touch moved to : (touchPoint)")
            erase(fromPoint: eraserStartPoint!, toPoint: touchPoint)
            eraserStartPoint = touchPoint
        }
    }
  
 override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first as UITouch?{
            let touchPoint = touch.location(in: self.lassoImageView)   lassoOffset!
            print("touch ended at : (touchPoint)")
            erase(fromPoint: touchPoint, toPoint: touchPoint)
            UIGraphicsBeginImageContext(lassoImageView.frame.size)
                lassoImageView.image?.draw(in: CGRect(x: 0, y: 0, width: lassoImageView.frame.size.width, height: lassoImageView.frame.size.height), blendMode: .normal, alpha: 1.0)
                lassoImageView.image?.draw(in:  CGRect(x: 0, y: 0, width: lassoImageView.frame.size.width, height: lassoImageView.frame.size.height), blendMode: .normal, alpha: 1.0)
                lassoImageView.image = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()   
    }
  
 func erase(fromPoint: CGPoint, toPoint: CGPoint) {
        UIGraphicsBeginImageContextWithOptions(lassoImageView.bounds.size, false, 1)
        //UIGraphicsBeginImageContext(lassoImageView.bounds.size)
        //UIGraphicsBeginImageContext(lassoImageView.image!.size)
        let context = UIGraphicsGetCurrentContext()
        lassoImageView.image?.draw(in: CGRect(x: 0, y: 0, width: lassoImageView.frame.size.width, height: lassoImageView.frame.size.height))
        //lassoImageView.image?.draw(in: calculateRectOfImageInImageView(imageView: lassoImageView))

        context?.move(to: fromPoint)
        context?.addLine(to: toPoint)

        context?.setLineCap(.round)
        context?.setLineWidth(CGFloat(eraserBrushWidth))

        context?.setBlendMode(.clear)

        context?.strokePath()

        lassoImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        croppedImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()
    }
  
 lassoImageView // this is UIImageView where I'm loading image from gallery and then erasing image with my finger

lassoOffset // this is Float for touch offset because finger hides part of image
  

Код прост, и он действительно работает, но если соотношение сторон изображения отличается от соотношения сторон UIImageView. Режим содержимого UIImageView установлен на Aspect Fit , но в любом случае, когда я перетаскиваю палец, изображение растягивается, как если бы это было Scale to Fill

Я считаю, что проблема в моем rect в этой строке:

 lassoImageView.image?.draw(in: CGRect(x: 0, y: 0, width: lassoImageView.frame.size.width, height: lassoImageView.frame.size.height))
  

Я даже пытался вычислить изображение rect самостоятельно, но в этом случае изображение просто исчезло после touches begun

Возможно, мой вопрос новичок, и я, вероятно, упускаю что-то нелепое, но мне действительно нужно разобраться в этом.

Спасибо всем и хорошего дня

Лучший, Виктор

Ответ №1:

О боже…

Я только что сделал это

 override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first as UITouch?{
            let touchPoint = touch.location(in: self.lassoImageView)   lassoOffset!
            print("touch ended at : (touchPoint)")
            erase(fromPoint: touchPoint, toPoint: touchPoint)
            /*UIGraphicsBeginImageContext(lassoImageView.frame.size)
                lassoImageView.image?.draw(in: CGRect(x: 0, y: 0, width: lassoImageView.frame.size.width, height: lassoImageView.frame.size.height), blendMode: .normal, alpha: 1.0)
                lassoImageView.image?.draw(in:  CGRect(x: 0, y: 0, width: lassoImageView.frame.size.width, height: lassoImageView.frame.size.height), blendMode: .normal, alpha: 1.0)
                lassoImageView.image = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()   */
    }
  

и в моем erase методе изменил эти строки:

 lassoImageView.image?.draw(in: CGRect(x: 0, y: 0, width: lassoImageView.frame.size.width, height: lassoImageView.frame.size.height))
  

к этому:

 lassoImageView.layer.render(in: context!)
  

Не уверен, что здесь происходит, но теперь это отлично работает

Комментарии:

1. Эй, вы реализовали функцию «восстановить»?