How to change UIKit UIImage: drawInRect method for AppKIt NSImage: drawInRect method

I port the iphone application to the Mac application, there I need to change the entire class associated with UIKit to AppKit. if you can help me really appreciate it. This is the best way to make lower parts.

Iphone App β†’ using UIKit

UIGraphicsPushContext(ctx); [image drawInRect:rect]; UIGraphicsPopContext(); 

Mac Os - Using AppKit

 [NSGraphicsContext saveGraphicsState]; NSGraphicsContext * nscg = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:YES]; [NSGraphicsContext setCurrentContext:nscg]; NSRect rect = NSMakeRect(offset.x * scale, offset.y * scale, scale * size.width, scale * size.height); [NSGraphicsContext restoreGraphicsState]; [image drawInRect:rect fromRect:NSMakeRect( 0, 0, [image size].width, [image size].height ) operation:NSCompositeClear fraction:1.0]; 
+4
source share
1 answer

Documents and documents are your friends; they will explain a lot of things that you misuse here.

 [NSGraphicsContext saveGraphicsState]; NSGraphicsContext * nscg = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:YES]; [NSGraphicsContext setCurrentContext:nscg]; 

You save the state of the graphics in the current context, and then immediately create a new context and set it as the current one.

 NSRect rect = NSMakeRect(offset.x * scale, offset.y * scale, scale * size.width, scale * size.height); 

That, apparently, is all you need. Creating a rectangle does not affect gstate, since it is not a drawing operation (a rectangle is just a set of numbers, you are not drawing a rectangle here).

In addition, you must use the current transformation matrix for the scale.

 [NSGraphicsContext restoreGraphicsState]; 

And then you are grestore in the context you created, and not the one you came across.

[Edit] Looking at this again after a year and a half, I think you misinterpreted the saveGraphicsState and restoreGraphicsState methods as the equivalent of UIGraphicsPushContext and UIGraphicsPopContext . They are not; saveGraphicsState and restoreGraphicsState click and select the graphical state of the current context. The current context is managed separately ( setCurrentContext: and does not have a push / pop API. [/ Edit]

I assume that you are using the CALayer drawInContext: method? If it is in NSView, then you already have the current context and do not (and should not) create it.

 [image drawInRect:rect fromRect:NSMakeRect( 0, 0, [image size].width, [image size].height ) operation:NSCompositeClear fraction:1.0]; 

The NSCompositeClear operation clears destination pixels, such as the Eraser tool in your favorite paint program. He does not draw an image. You want the NSCompositeSourceOver operation .

+5
source

Source: https://habr.com/ru/post/1307532/


All Articles