2016-09-12 49 views
1

我想从Swift中的多个UIBezierPath数组创建UIImage。在Swift中从Uibezierpath数组创建UIImage

我尝试以下的代码:

func convertPathsToImage(paths: [UIBezierPath]) -> UIImage{ 

    let imageWidth: CGFloat = 200 
    let imageHeight: CGFloat = 200 

    let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()! 
    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue) 
    let context = CGBitmapContextCreate(nil, Int(imageWidth), Int(imageHeight), 8, 0, colorSpace, bitmapInfo.rawValue) 

    CGContextBeginPath(context); 

    UIColor.blackColor().set() 

    for path in paths{ 
     path.stroke() 
    } 

    let newImageRef = CGBitmapContextCreateImage(context); 
    let newImage = UIImage(CGImage: newImageRef!) 

    return newImage 

    } 

结果是一个空的图像。

有人能解释我我做错了什么吗?非常感谢你!

+0

您是否将这些路径添加到视图的图层? – EridB

+0

@EridB号我不想将它们添加到视图的图层 –

+0

可以附加'[UIBezierPath]'阵列的具体示例吗? –

回答

1

我不能告诉你你做错了什么,但我有一个类似的问题,这段代码适合我。

func convertPathsToImage(paths: [UIBezierPath]) -> UIImage 
{ 
    let imageWidth: CGFloat = 200 
    let imageHeight: CGFloat = 200 
    let strokeColor:UIColor = UIColor.blackColor() 

    // Make a graphics context 
    UIGraphicsBeginImageContextWithOptions(CGSize(width: imageWidth, height: imageHeight), false, 0.0) 
    let context = UIGraphicsGetCurrentContext() 

    CGContextSetStrokeColorWithColor(context, strokeColor.CGColor) 

    for path in paths { 
     path.stroke() 
    } 
    let image = UIGraphicsGetImageFromCurrentImageContext() 

    UIGraphicsEndImageContext() 

    return image 
} 
+0

感谢您的回复。我发现了另一个解决方案,但我猜你的代码也可以。我会接受它作为正确的答案。 –