如何在两点之间画一条线

时间:2016-01-14 12:30:36

标签: ios swift uiimageview swift2

在我的应用程序中,我有一个UIImageView,我可以在其中绘制。 如何以这种方式在两点之间画一条线: 用户在UIImageView内按下,当按下代码时,代码会在第一个CGPoint和最后一个CGPoint之间创建一行。

这是我用来绘制的代码(在touchesMoved委托内):

    let touch = touches.first

    let currentPoint = touch!.locationInView(imageView)

    let context = UIGraphicsGetCurrentContext()

    UIGraphicsBeginImageContext(self.imageView.frame.size)
    self.imageView.image?.drawInRect(CGRectMake(0, 0, self.imageView.frame.size.width,self.imageView.frame.size.height))
    CGContextMoveToPoint(context, lastPoint.x, lastPoint.y)
    CGContextAddLineToPoint(context, currentPoint.x, currentPoint.y)
    CGContextSetLineCap(context,.Butt)
    CGContextSetLineWidth(context, 2.0)
    CGContextSetRGBStrokeColor(context,1.0, 1.0, 1.0, 1.0)
    CGContextStrokePath(context)
    self.imageView.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    lastPoint = currentPoint

1 个答案:

答案 0 :(得分:0)

尝试切换这两行的顺序:

let context = UIGraphicsGetCurrentContext()

UIGraphicsBeginImageContext(self.imageView.frame.size)

由于您不在drawRect方法中,UIGraphicsGetCurrentContext()很可能最初会返回nil,因此您将无所事事。在开始图像上下文后,UIGraphicsGetCurrentContext()应返回该上下文。

相关问题