创建从斯威夫特Uibezierpath数组的UIImage(Create an UIImage fr

2019-09-27 08:28发布

我想创建从斯威夫特多个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
}

结果是一个空的图像。

有人可以解释我什么我真的做错了吗? 非常感谢你!

Answer 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
}


文章来源: Create an UIImage from Uibezierpath Array in Swift