简体   繁体   中英

Force redraw of a UIView or CALayer on scale/transform

Say you have a UIView or a CALayer that does its own (vector) drawing, and you want it to remain crisp at any size, even when scaling the view or layer. How can I make it redraw when it is scaled with the transform property? Is the only way to do to force a bounds change instead of using the transform ? Or to call setNeedsDisplay at every step?

Why do UIImageView seem to behave differently (ie it seems to always scale its source image appropriately, even when it is scaled with transform and the bounds doesn't change)? Is it because it's the only case where the content property of the underlying CALayer is set directly?

if needsDisplayOnBoundsChange on the CALayer is not enough in your case, you can subclass CALayer and implement the + (BOOL)needsDisplayForKey:(NSString *)key method. Example:

+ (BOOL)needsDisplayForKey:(NSString *)key {
    if ([key isEqualToString:@"transform"]) {
        return YES;
    }
    return [super needsDisplayForKey:key];
}

now your layer should be redrawn everytime the transform property changes. This might cause performance issues in animations if your drawing is extensive.

For vector based layers, you can use CAShapeLayer . This specalised layer takes a path and will redraw as needed to keep the layer looking crisp.

Create a CGPathRef and assign it to the layer's path :

shapeLayer.path = myPath;

You could manually handle the setTransform method of your custom view. A simplified version for handling scaling events could simply be

-(void)setTransform:(CGAffineTransform)transform
{
    CGRect bounds = self.bounds;
    bounds.size.width *= transform.a;
    bounds.size.height *= transform.d;
    self.bounds = bounds;
}

This would just actually resize your view (and cause a redraw), rather than stretching an image.

您可以使用self.contentMode = UIViewContentMode.redraw

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM