简体   繁体   English

如何在两点之间画一条线

[英]How to drawing a line between two points

In my app I have an UIImageView where I can draw inside of that. 在我的应用程序中,我有一个UIImageView可以在其中绘制。 How to draw a lines between two points in this way: The user press inside the UIImageView and when leave the press the code create the lines between the first CGPoint and the last CGPoint . 如何以这种方式在两点之间画一条线:用户在UIImageView按下,当按下时,代码在第一个CGPoint和最后一个CGPoint之间创建线。

This is the code I've used to let drawing (Inside a touchesMoved delegate): 这是我用来绘制的代码(在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

Try switching the order of these two lines: 尝试切换这两行的顺序:

let context = UIGraphicsGetCurrentContext()

UIGraphicsBeginImageContext(self.imageView.frame.size)

Since you're not in a drawRect method, it is very likely that UIGraphicsGetCurrentContext() will return nil initially, so you will be drawing to nothing. 由于您不在drawRect方法中,因此UIGraphicsGetCurrentContext()最初很可能返回nil ,因此您将一无所获。 After you begin an image context, UIGraphicsGetCurrentContext() should return that context. 开始图像上下文之后, UIGraphicsGetCurrentContext()应该返回该上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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