Creating images from views, strings, etc
Ok so I have a problem. I have a method that is called imageFromText, it requires one parameter, the string itself, and it returns a NSImage. I also have another one which is called: imageFromView, this one basically have to "take a screenshot" of the view and return a NSImage, it also has only one parameter, the view itself. So it looks like this:
-(NSImage*)imageFromText: (NSString*)text {
}
-(NSImage*)imageFromView: (NSView*)view {
}
There's only one problem, I have no idea how to do this. Well so, I spent my afternoon searching around 开发者_运维知识库and I didn't find nothing. I've tried, to the second one, a method dataWithPDFInsideRect, but obviously, this method was not made to this propose. Please help me out!. PLEASE NOT: I'M NOT ASKING FOR THE CODE READY. LIKE THE OLD DICTATION (IN MY COUNTY): DON'T GIVE THEM THE FISH, THEACH THEM HOW TO FISH. (TRANSLATED).
An alternative way is to lock focus on the view, then create a bitmap image rep with the contents of the view's bounds. You can then create a blank image whose size is the size of the bounds, and add the image rep to it.
The third way is dataWithPDFInsideRect:
. Yes, the one you tried and couldn't get to work (I wish you'd explained what problem you had with it instead of just dismissing it!). Pass the view's bounds, then pass the data to NSImage's initWithData:
.
As for imageFromView: check the Organizer Documentation for Screen Capture
.
And imageFromText: You want an image (PNG I assume) that just shows a text? Don't you want to specify things like image size, font size, font color, background color, ...?
Summarizing, lock focus on the image, then draw. The NSImage docs should have more if you search for lockFocus.
The methods you're interested in are:
-[NSImage lockFocus]
+[NSGraphicsContext currentContext]
-[NSView displayRectIgnoringOpacity:inContext:]
-[NSImage lockFocus]
To draw to an image, allocate one, and then lock focus on it, then issue drawing calls and then unlock focus.
To draw a view into an image, lock focus on an image, get the current graphic context (which is now the image), and pass that to -[NSView displayRectIgnoringOpacity:inContext:].
精彩评论