我想在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
}
结果是空图像。
有人可以解释一下我做错了什么吗?非常感谢你!
答案 0 :(得分: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
}