When do I need to set the contentsScale property of a CALayer?

前端 未结 3 684
故里飘歌
故里飘歌 2020-12-13 04:40

In the documentation Apple states that you need to consider the scale factor of a layer when it:

  • Creates additional Core Animation layers with
3条回答
  •  -上瘾入骨i
    2020-12-13 05:12

    While a layer is almost always used inside a view, the layer may have been created ad-hoc and added as a sublayer of the view's layer, or assigned as another layer's mask. In both instances, the contentsScale property would have to be set. For example:

    UIView *myMaskedView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    CALayer *myMaskLayer = [CALayer new];
    myMaskLayer.frame = myMaskedView.bounds;
    UIImage *maskImage = [UIImage imageNamed:@"some_image"];
    myMaskLayer.contents = (id)maskImage.CGImage;
    myMaskLayer.contentsScale = maskImage.scale;
    myMaskedView.layer.mask = myMaskLayer;
    

    You may also want to build a hierarchy of layers for performing animations, without using each layer to back a view:

    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    
    CALayer *sublayerA = [CALayer new];
    sublayerA.contentsScale = myView.layer.contentsScale;
    [myView.layer addSublayer:sublayerA];
    
    CALayer *sublayerB = [CALayer new];
    sublayerB.contentsScale = myView.layer.contentsScale;
    [myView.layer addSublayer:sublayerB];
    
    // Continue adding layers   
    

    This is especially important for Retina devices, which have a native screen scale of 2.0; a layer with the default scale of 1.0 would display noticeable pixelation.

提交回复
热议问题