【问题标题】:Create an UIImage from Uibezierpath Array in Swift在 Swift 中从 Uibezierpath 数组创建 UIImage
【发布时间】:2016-09-12 13:29:12
【问题描述】:

我想在 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
}

结果是一个空图像。

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

【问题讨论】:

  • 您是否将这些路径添加到视图层?
  • @EridB 不,我不想将它们添加到视图层
  • 你能附上[UIBezierPath]数组的具体例子吗?
  • @ShadowOf 为什么会有帮助? UIBezierPaths 数组中有什么特别之处?无论如何我解决了这个问题,稍后会在这里发布我的答案。

标签: ios swift uiimage uibezierpath


【解决方案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
}

【讨论】:

  • 感谢您的回复。我找到了另一个解决我的问题的方法,但我想你的代码也可以。我会接受它作为正确答案。
  • 很抱歉,这不是完全正确的答案,它可以为我绘制 UIBezierPath 数组的一部分,如果我放大图像的宽度和高度,那就对了,顺便说一句你能分享您的解决方案。?
  • @JonasSchafft 请发布您的“我的问题的另一种解决方案”作为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
相关资源
最近更新 更多