Create an UIImage from Uibezierpath Array in Swift

那年仲夏 提交于 2019-12-11 08:44:56

问题


I want to create an UIImage from an Array of multiple UIBezierPaths in Swift.

I tried the following code:

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
}

The Result is an empty image.

Can someone explain me what i`m doing wrong? Thank you very much!


回答1:


I can't tell you what you are doing wrong, but I had a similar issue, and this code works for me.

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
}


来源:https://stackoverflow.com/questions/39451491/create-an-uiimage-from-uibezierpath-array-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!