ios – 使用Swift 3.0实时绘制一条线

前端之家收集整理的这篇文章主要介绍了ios – 使用Swift 3.0实时绘制一条线前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在UI ImageView上绘图.使用 Swift 1.2我能够让它工作,但我不得不将它转换为swift 3.0而我无法让它工作.

它需要做的是用手指准确地绘制你在屏幕上绘制的内容.

代码没有错误,但只是没有显示任何内容.

变量;

var lastPoint = CGPoint.zero
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var brushWidth: CGFloat = 10.0
var opacity: CGFloat = 1.0
var swiped = false

代码;

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

func drawLineFrom(fromPoint: CGPoint,toPoint: CGPoint) {


    imageView.image?.draw(in: CGRect(x: 0,y: 0,width: view.frame.size.width,height: view.frame.size.height))
    UIGraphicsBeginImageContext(self.imageView.bounds.size);
    let context = UIGraphicsGetCurrentContext()

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

        context?.setLineCap(CGLineCap.round)
        context?.setLineWidth(brushWidth)
        context?.setStrokeColor(red: red,green: green,blue: blue,alpha: 1.0)
        context?.setBlendMode(CGBlendMode.normal)

        imageView.image = UIGraphicsGetImageFromCurrentImageContext()
        imageView.alpha = opacity
        UIGraphicsEndImageContext()

}

override func touchesMoved(_ touches: Set<UITouch>,with event: UIEvent?) {
    swiped = true
    if let touch = touches.first {
        let currentPoint = touch.location(in: view)
        drawLineFrom(fromPoint: lastPoint,toPoint: currentPoint)

        lastPoint = currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>,with event: UIEvent?) {
    if !swiped {
                    // draw a single point
        self.drawLineFrom(fromPoint: lastPoint,toPoint: lastPoint)
    }

解决方法

你必须开始图像上下文:
UIGraphicsBeginImageContextWithOptions(view.bounds.size,false,0)

你还必须克服这条道路:

context?.strokePath()

您也没有绘制上一张图片

imageView.image?.draw(in: view.bounds)

从而:

func drawLine(from fromPoint: CGPoint,to toPoint: CGPoint) {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size,0)

    imageView.image?.draw(in: view.bounds)

    let context = UIGraphicsGetCurrentContext()

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

    context?.setLineCap(CGLineCap.round)
    context?.setLineWidth(brushWidth)
    context?.setStrokeColor(red: red,alpha: 1.0)
    context?.setBlendMode(CGBlendMode.normal)
    context?.strokePath()

    imageView.image = UIGraphicsGetImageFromCurrentImageContext()
    imageView.alpha = opacity
    UIGraphicsEndImageContext()
}
原文链接:https://www.f2er.com/iOS/328180.html

猜你在找的iOS相关文章