UIImage vs NSImage: Drawing to an off screen image in iOS

半世苍凉 提交于 2020-01-22 11:50:06

问题


In mac osx (cocoa), It is very easy to make a blank image of a specific size and draw to it off screen:

NSImage* image = [[NSImage alloc] initWithSize:NSMakeSize(64,64)];
[image lockFocus];
/* drawing code here */
[image unlockFocus];

However, in iOS (cocoa touch) there does not seem to be equivalent calls for UIImage. I want to use UIImage (or some other equivalent class) to do the same thing. That is, I want to make an explicitly size, initially empty image to which I can draw using calls like UIRectFill(...) and [UIBezierPath stroke].

How would I do this?


回答1:


CoreGraphics is needed here, as UIImage does not have high level functions like what you explained..

UIGraphicsBeginImageContext(CGSizeMake(64,64));

CGContextRef context = UIGraphicsGetCurrentContext();
// drawing code here (using context)

UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();



回答2:


You can do that as follows:

UIGraphicsBeginImageContext(CGSizeMake(64, 64));
//Drawing code here
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

Here is Apple's Graphics and Drawing reference.




回答3:


Something like this:

UIGraphicsBeginImageContextWithOptions(mySize, NO, 0.0f);       
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(context);

[myImage drawInRect:myImageRect];
[myText drawAtPoint:myOrigin withFont:myFont];

UIGraphicsPopContext();
UIImage *myNewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


来源:https://stackoverflow.com/questions/9829475/uiimage-vs-nsimage-drawing-to-an-off-screen-image-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!