Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGContext text drawing doesn't scale up on iPhone 4

I am trying to create an app that scales up nicely on the iPhone 4. Currently most of it scales up perfectly, except for one crucial piece: the text that I draw inside a CALayer, inside its drawInContext: method. Here is my code:

- (void)drawInContext:(CGContextRef)context {
    UIGraphicsPushContext(context);

    CGContextSetGrayFillColor(context, 1.0f, 1.0f);
    CGContextFillRect(context, self.bounds);

    CGContextSetAllowsAntialiasing(context, true);
    CGContextSetShouldAntialias(context, true);

    CGContextSetAllowsFontSmoothing(context, true);
    CGContextSetShouldSmoothFonts(context, true);

    CGContextSetAllowsFontSubpixelQuantization(context, true);
    CGContextSetShouldSubpixelQuantizeFonts(context, true);

    CGContextTranslateCTM(context, 0.0f, self.frame.size.height);
    CGContextScaleCTM(context, 1.0f, -1.0f);

    CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]);
    CGContextSelectFont(context, "CardKit", 30.0f, kCGEncodingMacRoman);
    CGContextSetTextDrawingMode(context, kCGTextFill);
    CGContextShowText(context, "A", sizeof("A"));

    UIGraphicsPopContext();
}

This short produce crisp text on both devices, but unfortunately, it produces blurry text on both. Here is how it appears:

ugly text http://files.droplr.com.s3.amazonaws.com/files/16285043/1gBp61.Screen%20shot%202010-06-26%20at%2021:25:09.png

That image is taken at 100% zoom on the iPhone 4. What in the world? Any ideas how I can fix this?

like image 769
Carter Allen Avatar asked Jun 27 '10 03:06

Carter Allen


3 Answers

You should set the layer's contentsScale to be the same as the scale of your screen:

layer.contentsScale = [UIScreen mainScreen].scale;

This will scale it correctly on all iOS devices, Retina Display and non-Retina Display. You shouldn't hard-code it to 2.0 (or anything else for that matter) unless you have a good reason to do so.

like image 122
Nick Forge Avatar answered Sep 22 '22 03:09

Nick Forge


The link of the previous answer is broken now. New link is this one.

like image 25
Jean-Pierre Matsumoto Avatar answered Sep 25 '22 03:09

Jean-Pierre Matsumoto


Since you're dealing with CALayers, you need to set the contentsScale property of your layer to 2.0.

See this section in the iPhone Application programming guide for iOS 4.

like image 33
Jason Foreman Avatar answered Sep 24 '22 03:09

Jason Foreman