用UIBezierPath画一条线 [英] Draw a line with UIBezierPath

查看:109
本文介绍了用UIBezierPath画一条线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首次使用BezierPaths,想知道这个函数实际上应该如何实现。目前bezier路径在图像的框架内移动,而不是在屏幕上绘图。

First time using BezierPaths, wondering how this function is actually supposed to be implemented. Currently the bezier path moves within the frame of the image, as opposed to drawing on screen.

有更好的方法吗?

func drawLineFromPoint(start : CGPoint, toPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) {

    var maxWidth = abs(start.x - end.x)
    var maxHeight = abs(start.y - end.y)

    var contextSize : CGSize!
    if maxWidth == 0 {
        contextSize = CGSize(width: 1, height: maxHeight)
    }else {
        contextSize = CGSize(width: maxWidth, height: 1)
    }

    //design the path
    UIGraphicsBeginImageContextWithOptions(contextSize, false, 0)
    var path = UIBezierPath()
    path.lineWidth = 1.0
    lineColor.set()

    //draw the path and make visible
    path.moveToPoint(start)
    path.addLineToPoint(end)
    path.stroke()

    //create image from path and add to subview
    var image = UIGraphicsGetImageFromCurrentImageContext()
    var imageView = UIImageView(image: image)
    view.addSubview(imageView)
    UIGraphicsEndImageContext()
}


推荐答案

结束这样做:

func drawLineFromPoint(start : CGPoint, toPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) {

    //design the path
    var path = UIBezierPath()
    path.moveToPoint(start)
    path.addLineToPoint(end)

    //design path in layer
    var shapeLayer = CAShapeLayer()
    shapeLayer.path = path.CGPath
    shapeLayer.strokeColor = lineColor.CGColor
    shapeLayer.lineWidth = 1.0

    view.layer.addSublayer(shapeLayer)
}

这篇关于用UIBezierPath画一条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆