简体   繁体   中英

Draw straight line swift 4

maybe a simple question. I am trying to make an app where you can draw straight lines: horizontal vertical and diagonal. I am also trying to give measurements to the lines (don`t get this working yet..)

I have fixed that I can draw lines but not straight (like a pencil without ruler can't find any documentation on the web to draw straight lines)

import UIKit
import Foundation
class tekengedeelte: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate  {


    @IBOutlet weak var tekenview: UIView!

    var path = UIBezierPath()
    var startPoint = CGPoint()
    var touchPoint = CGPoint()
    var setSigImage: ((_ data: UIImage) -> ())?
    var setcameraimage: ((_ data: UIImage) -> ())?

    override func viewDidLoad() {
        super.viewDidLoad()
        tekenview.layer.shadowOpacity = 1
        tekenview.layer.shadowRadius = 10
        tekenview.layer.shadowOffset = CGSize(width: 1, height: 1)
        tekenview.layer.shadowColor = UIColor.black.cgColor
        //tekenview.layer.shadowPath = UIBezierPath(rect: tekenview.bounds).cgPath
        tekenview.layer.shadowPath = CGPath(rect: tekenview.bounds, transform: nil)
        tekenview.layer.shouldRasterize = true

        tekenview.clipsToBounds = true
        tekenview.isMultipleTouchEnabled = false
    }

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

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        if let point = touch?.location(in: tekenview) {
            touchPoint = point
        }

        path.move(to: startPoint)
        path.addLine(to: touchPoint)
        startPoint = touchPoint

        draw()
    }

    func draw() {
        let strokeLayer = CAShapeLayer()
        strokeLayer.fillColor = UIColor.black.cgColor
        strokeLayer.lineWidth = 5
        strokeLayer.strokeColor = UIColor.black.cgColor
        strokeLayer.path = path.cgPath
        tekenview.layer.addSublayer(strokeLayer)
        tekenview.setNeedsDisplay()
    }

    @IBAction func clearPressed(_ sender: UIButton) {
        path.removeAllPoints()
        tekenview.layer.sublayers = nil
        tekenview.setNeedsDisplay()
    }

    @IBAction func setPressed(_ sender: UIButton) {

        // Convert CanvasView to UIImage
        let renderer = UIGraphicsImageRenderer(size: tekenview.bounds.size)
        let image = renderer.image { ctx in
            view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        }

        // Send image back to onboarding screen
        setSigImage?(image)

        // Rotate device back to portrait mode
        //let appDelegate = UIApplication.shared.delegate as! AppDelegate
       //appDelegate.r = .portrait


        // Close modal window
        dismiss(animated: true)
    }
    //foto maken
    @IBAction func camera(_ sender: UIButton) {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera){
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerController.SourceType.camera;
            imagePicker.allowsEditing = false
            self.present(imagePicker, animated: true, completion: nil)
        }
    }

    @IBAction func photolibraryaction(_ sender: UIButton) {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary) {
            let imagepicker = UIImagePickerController()
            imagepicker.delegate = self
            imagepicker.sourceType = UIImagePickerController.SourceType.photoLibrary;
            imagepicker.allowsEditing = true
            self.present(imagepicker, animated: true, completion: nil)
        }

    }
}

As Reinier Melian explained drawing straight line using core graphics. When the touch ended draw the save image using CGContext to show in UIImageView.

You need keep the current context until the line draw process has ended, after that you need keep the current image and clear the context , draw the saved image again, and draw the new line. When the touch ended is called clean the current context and save the current image, after that start the new line draw process again.

import UIKit

class ViewController2: UIViewController {

    @IBOutlet weak var drawingPlace: UIImageView!

    var startTouch : CGPoint?
    var secondTouch : CGPoint?
    var currentContext : CGContext?
    var prevImage : UIImage?


    override func viewDidLoad() {
        super.viewDidLoad()
    }


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

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        for touch in touches{
            secondTouch = touch.location(in: drawingPlace)

            if(self.currentContext == nil){
                UIGraphicsBeginImageContext(drawingPlace.frame.size)
                self.currentContext = UIGraphicsGetCurrentContext()
            }else{
                self.currentContext?.clear(CGRect(x: 0, y: 0, width: drawingPlace.frame.width, height: drawingPlace.frame.height))
            }

            self.prevImage?.draw(in: self.drawingPlace.bounds)

            let bezier = UIBezierPath()

            bezier.move(to: startTouch!)
            bezier.addLine(to: secondTouch!)
            bezier.close()

            UIColor.blue.set()

            self.currentContext?.setLineWidth(4)
            self.currentContext?.addPath(bezier.cgPath)
            self.currentContext?.strokePath()
            let img2 = self.currentContext?.makeImage()
            drawingPlace.image = UIImage.init(cgImage: img2!)

        }
    }


    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

        self.currentContext = nil
        self.prevImage = self.drawingPlace.image
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM