【问题标题】:Get UIImage from an array of points从点数组中获取 UIImage
【发布时间】:2015-08-17 20:14:37
【问题描述】:

我有一个 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中回答:)

【问题讨论】:

  • points 来自哪里?怎么不是[CGPoint](你得把if let改成CGPoint)?
  • points 是从用 obj-C 编写的闭源框架返回的 NSArray。我应该先转换为 [CGPoint] 吗?有什么优势?

标签: ios swift uiimage uibezierpath


【解决方案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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 有道理。你觉得我的画线代码怎么样?
    • @JonSetting 您可以使用 CoreGraphics 函数而不是 UIBezierPath,因为它只是一个包装器。此外,如果您不需要曲线,那么最好使用直线。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多