iOS: How do I support Retina Display with CGLayer?

前端 未结 2 1582
情书的邮戳
情书的邮戳 2021-01-30 04:51

I\'m drawing a graph on a CALayer in its delegate method drawLayer:inContext:.

Now I want to support Retina Display, as the graph looks blurry on the latest

相关标签:
2条回答
  • 2021-01-30 05:08

    I decided not to use CGLayer and directly draw on the graphics context of the CALayer, and now it's drawn nicely in high resolution on retina display.

    I found the similar question here, and found that there is no point of using CGLayer in my case.

    I used CGLayer because of the Apple's sample program "Using Multiple CGLayer Objects to Draw a Flag" found in the Quartz 2D Programming guide. In this example, it creates one CGLayer for a star and uses it multiple times to draw 50 stars. I thought this was for a performance reason, but I didn't see any performance difference.

    For the purpose of cutting off the graph lines exceeding the edge of the layer, I decided to use multiple CALayers.

    0 讨论(0)
  • 2021-01-30 05:24

    This is how to draw a CGLayer correctly for all resolutions.

    1. When first creating the layer, you need to calculate the correct bounds by multiplying the dimensions with the scale:

      int width = 25; 
      int height = 25;
      float scale = [self contentScaleFactor];
      CGRect bounds = CGRectMake(0, 0, width * scale, height * scale);
      CGLayer layer = CGLayerCreateWithContext(context, bounds.size, NULL);
      CGContextRef layerContext = CGLayerGetContext(layer);
      
    2. You then need to set the correct scale for your layer context:

      CGContextScaleCTM(layerContext, scale, scale);
      
    3. If the current device has a retina display, all drawing made to the layer will now be drawn twice as large.

    4. When you finally draw the contents of your layer, make sure you use CGContextDrawLayerInRect and supply the unscaled CGRect:

      CGRect bounds = CGRectMake(0, 0, width, height);
      CGContextDrawLayerInRect(context, bounds, layerContext);
      

    That's it!

    0 讨论(0)
提交回复
热议问题