Ios 从点数组中获取UIImage
我有一个CGPoint对象数组。数组表示一条线。元素0是此行的起点。元素1是下一个点,依此类推。我知道我想给线条加什么颜色和像素厚度。我想以包含此行的UIImage结束。我正在考虑这样做:Ios 从点数组中获取UIImage,ios,swift,uiimage,uibezierpath,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
// 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()
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);
这样行吗?有没有标准或更好的方法来实现这一点?请在目标C中自由回答:)如果您的绘图很复杂,并且您希望它会很耗时,那么最好使用位图并在后台线程中绘制,如下所示:
// 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()
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
,必须循环通过这些点。但您可能希望移动到第一个点,然后附加后续点:
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)
}
@John Tracid方法的一个优点是可以使用CGContextRef
函数。虽然UIBezierPath
没有从N+1点数组构造N段多段线的便利功能,CGContextRef
有:
CGContextAddLines(bitmap, points, points.count) // might need a magical cast here
有道理。你觉得我的绘制线代码怎么样?@JonSetting你可以使用CoreGraphics函数而不是
UIBezierPath
,因为它只是一个包装器。如果你不需要曲线,最好使用直线。点从哪里来?为什么它不是[CGPoint]
(如果让进入CGPoint
,你必须)?points是从用obj-C编写的封闭源代码框架返回的NSArray。我应该先转换为[CGPoint]吗?有什么好处?