当前位置:   MFC > 正文

如何从当前图形上下文创建UIImage?

core-graphics,quartz-graphics,uiimage,ios,go,webview,DevBox,在线流程图,编程,编程问答,程序员,开发者工具,开发工具,json解析,二维码生成,unix时间戳,在线开发工具,前端开发工具,开发人员工具,站长工具

我想从当前的图形上下文创建一个UIImage对象.更具体地说,我的用例是用户可以绘制线条的视图.他们可以逐步绘制.完成后,我想创建一个UIImage来代表他们的绘图.

这是drawRect:现在对我来说是这样的:

- (void)drawRect:(CGRect)rect
{
CGContextRef c = UIGraphicsGetCurrentContext();

CGContextSaveGState(c);
CGContextSetStrokeColorWithColor(c, [UIColor blackColor].CGColor);
CGContextSetLineWidth(c,1.5f);

for(CFIndex i = 0; i < CFArrayGetCount(_pathArray); i++)
{
    CGPathRef path = CFArrayGetValueAtIndex(_pathArray, i);
    CGContextAddPath(c, path);
}

CGContextStrokePath(c);

CGContextRestoreGState(c);
}

...其中_pathArray的类型为CFArrayRef,并且每次调用touchesEnded:时都会填充.另请注意,drawRect:可以在用户绘制时多次调用.

用户完成后,我想创建一个表示图形上下文的UIImage对象.有关如何做到这一点的任何建议?



1> 小智..:

您需要先设置图形上下文:

UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();



2> Ben Gotow..:

UIImage*image = UIGraphicsGetImageFromCurrentImageContext();

如果你需要留下image来,一定要保留它!

编辑:如果要将drawRect的输出保存到图像,只需使用创建位图上下文UIGraphicsBeginImageContext并使用新的上下文绑定调用drawRect函数.这比在drawRect中保存您正在使用的CGContextRef更容易 - 因为该上下文可能没有与之关联的位图信息.

UIGraphicsBeginImageContext(view.bounds.size);
[view drawRect: [myView bounds]];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

您也可以使用Kelvin提到的方法.如果您想从更复杂的视图(如UIWebView)创建图像,他的方法会更快.绘制视图的图层不需要刷新图层,只需要将图像数据从一个缓冲区移动到另一个缓冲区!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/MFC/detail/21522
推荐阅读
相关标签
  

闽ICP备14008679号