如何从CGContextRef获取UIImage?

sam*_*ize 8 iphone core-graphics quartz-2d

我有一个CGContextRef,我用位图上下文做了我的绘图.

现在,我希望有一个函数调用来获取CGContextRef的UIImage.我怎么做?

Nyx*_*0uf 26

像这样的东西:

-(UIImage*)doImageOperation
{
  // Do your stuff here
  CGImageRef imgRef = CGBitmapContextCreateImage(context);
  UIImage* img = [UIImage imageWithCGImage:imgRef];
  CGImageRelease(imgRef);
  CGContextRelease(context);
  return img;
}
Run Code Online (Sandbox Code Playgroud)

  • 这仅在 `context` 是 CGBitmapContext 时有效;它可能不适用于任何其他类型的 CGContext。@samwize:您应该将其命名为不同的名称。前缀是命名空间的约定;Apple 可能会随时添加一个名为`UIGraphicsGetImageFromImageContext` 的函数,无论是公共的还是私有的,如果他们这样做了,你的就会出现问题。使用您自己的前缀。 (2认同)

Ech*_*lon 5

已针对Swift 3进行了更新,这是一个便捷功能,它使用CGContext并返回UIImage。请注意,在Swift 3中使用完上下文后,您不再需要释放上下文。

func imageFromContext(_ context: CGContext) -> UIImage? {
    guard let cgImage = context.makeImage() else { return nil }
    return UIImage.init(cgImage: cgImage)
}
Run Code Online (Sandbox Code Playgroud)