Scaling UITextView using contentScaleFactor property

前端 未结 3 418
面向向阳花
面向向阳花 2020-12-16 07:37

I am trying to create a higher resolution image of a UIView, specifically UITextView.

This question and answer is exactly what I am trying

3条回答
  •  粉色の甜心
    2020-12-16 08:26

    Setting the contentScaleFactor and contentsScale is in fact the key, as @dbotha pointed out, however you have to walk the view and layer hierarchies separately in order to reach every internal CATiledLayer that actually does the text rendering. Adding the screen scale might also make sense.

    So the correct implementation would be something like this:

    - (void)updateForZoomScale:(CGFloat)zoomScale {
        CGFloat screenAndZoomScale = zoomScale * [UIScreen mainScreen].scale;
        // Walk the layer and view hierarchies separately. We need to reach all tiled layers.
        [self applyScale:(zoomScale * [UIScreen mainScreen].scale) toView:self.textView];
        [self applyScale:(zoomScale * [UIScreen mainScreen].scale) toLayer:self.textView.layer];
    }
    
    - (void)applyScale:(CGFloat)scale toView:(UIView *)view {
        view.contentScaleFactor = scale;
        for (UIView *subview in view.subviews) {
            [self applyScale:scale toView:subview];
        }
    }
    
    - (void)applyScale:(CGFloat)scale toLayer:(CALayer *)layer {
        layer.contentsScale = scale;
        for (CALayer *sublayer in layer.sublayers) {
            [self applyScale:scale toLayer:sublayer];
        }
    }
    

提交回复
热议问题