在Swift中从Uibezierpath数组创建一个UIImage

我想在Swift中从多个UIBezierPaths的数组创建一个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 } 

结果是一个空图像。

谁能解释一下我做错了什么? 非常感谢你!

我无法告诉你你做错了什么,但我遇到了类似的问题,这段代码对我有用。

 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 }