iOS中来自CALayer的UIImage [英] UIImage from CALayer in iOS
问题描述
在我的应用程序中,我创建了一个CALayer
(具有几个子层-CALayer由添加为子层的形状组成).
In my application, I have created a CALayer
(with a few sublayers - the CALayer is composed of shapes added as sublayers).
我正在尝试创建一个UIImage
,我可以将其上传到服务器(我有相应的代码).
但是,我不知道如何将CALayer
添加到UIImage
.
I am trying to create a UIImage
that I will be able to upload to a server (I have the code for this).
However, I can't figure out how to add the CALayer
to a UIImage
.
这可能吗?
推荐答案
听起来像您想将图层渲染到UIImage中.在这种情况下,下面的方法应该可以解决问题.只需将其添加到您的视图或控制器类中,或在CALayer上创建一个类别.
Sounds like you want to render your layer into a UIImage. In that case, the method below should do the trick. Just add this to your view or controller class, or create a category on CALayer.
Obj-C
- (UIImage *)imageFromLayer:(CALayer *)layer
{
UIGraphicsBeginImageContextWithOptions(layer.frame.size, NO, 0);
[layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return outputImage;
}
快速
func imageFromLayer(layer:CALayer) -> UIImage {
UIGraphicsBeginImageContextWithOptions(layer.frame.size, layer.isOpaque, 0)
layer.render(in: UIGraphicsGetCurrentContext()!)
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage!
}
这篇关于iOS中来自CALayer的UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!