从一系列点获取UIImage

时间:2015-08-17 20:14:38

标签: ios swift uiimage uibezierpath

我有一个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()

这会有用吗?有没有标准或更好的方法来做到这一点?请随意回答目标C:)

2 个答案:

答案 0 :(得分:1)

如果您的绘图很复杂并且您希望它会耗费时间,那么最好使用位图并在后台线程中绘制:

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);

答案 1 :(得分:1)

如果你想使用UIBezierPath,你必须遍历这些点。但是你可能想移动到第一点,然后追加后续点:

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