Jonas
Jonas

Reputation: 2249

Create an UIImage from Uibezierpath Array in Swift

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!

Upvotes: 1

Views: 1745

Answers (1)

rjpadula
rjpadula

Reputation: 969

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
}

Upvotes: 1

Related Questions