从点数组中获取 UIImage

Get UIImage from an array of points

我有一组 CGPoint 对象。该数组表示一条线。元素 0 是这条线的起点。元素 1 是下一个点,依此类推。我知道我想给线条赋予什么样的颜色和厚度(以像素为单位)。我想以包含此行的 UIImage 结束。我正在考虑做这样的事情:

// Get graphics context
UIGraphicsBeginImageContextWithOptions(imageSize, false, 1.0)

// Draw line
let line = UIBezierPath()
if let startingPoint = points.firstObject as? CGPoint {
    line.moveToPoint(startingPoint)
}

for point in points { // Would I need to ignore the first point?
    if let point = point as? CGPoint {
        line.addLineToPoint(point)
    }
}

// Obtain image and save to file

// End graphics context
UIGraphicsEndImageContext()

这行得通吗?有没有标准或更好的方法来做到这一点?欢迎在 Objective C 内回答:)

如果您的绘图很复杂并且您认为这会很耗时,那么最好使用位图并在后台线程中绘制,如下所示:

CGFloat imageWidth = 100;
CGFloat imageHeight = 100;

// create bitmat with prarameters you need
CGContextRef bitmap = CGBitmapContextCreate(...);
CGContextBeginPath(bitmap);

// your drawing here

// result image
CGImageRef newImageRef = CGBitmapContextCreateImage(bitmap);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];

// Clean up
CGContextRelease(bitmap);
CGImageRelease(newImageRef);

如果要使用UIBezierPath,则必须循环遍历这些点。但是您可能想要 移动 到第一个点,然后 append 后续点:

line.moveToPoint(points.first!) // assumes points is never empty, otherwise use an if let or other guard
for point in points[1..<points.count] { // skip the first one
    line.addLineToPoint(point)
}

或者您可以使用生成器:

var stream = points.generate()
line.moveToPoint(stream.next()!) // assumes points is never empty, otherwise use an if let or other guard
while let point = stream.next() {
    line.addLineToPoint(point)
}

@John Tracid 方法的一个优点是您可以使用 CGContextRef 函数。虽然 UIBezierPath 没有从 N+1 点数组构造 N 段折线的便利函数,但 CGContextRef 有:

CGContextAddLines(bitmap, points, points.count) // might need a magical cast here