iOS: How do I support Retina Display with CGLayer?

前端 未结 2 1587
情书的邮戳
情书的邮戳 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: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!

提交回复
热议问题