Search code examples
macosnsimagedrawinrect

Nsimage draw in rect but the image is blurry?


designer give me picture like this enter image description here

But when I use drawInRect API draw the picture in context, the picture is like this enter image description here

The size of the rect is just the size of the image.And the image is @1x and @2x.

the difference is very clear, the picture is blurry and there is a gray line in the right of image, and My imac is retina resolution.

================================================ I have found the reason,

[self.headLeftImage drawInRect:NSMakeRect(100,
                                        100,
                                        self.headLeftImage.size.width,
                                        self.headLeftImage.size.height)];




CGContextRef context = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
CGContextSaveGState(context);
CGContextTranslateCTM(context, self.center.x , self.center.y);

[self.headLeftImage drawInRect:NSMakeRect(100,
                                        100,
                                        self.headLeftImage.size.width,
                                        self.headLeftImage.size.height)];
CGContextRestoreGState(context);

And in the first draw the image will not blur, but after translate the image is blurry. Just like the picture:enter image description here


Solution

  • The problem is that you're translating the context to a non-integral pixel location. Then, the draw is honoring your request to put the image at a non-integral position, which causes it to be anti-aliased and color in some pixels partially.

    You should convert the center point to device space, integral-ize it (e.g. by using floor()), and then convert it back. Use CGContextConvertPointToDeviceSpace() and CGContextConvertPointToUserSpace() to do the conversions. That does the right thing for Retina and non-Retina displays.