Animate a UIView's CoreGraphics/drawRect conte

2019-04-12 11:45发布

问题:

Is it possible to animate a UIView's CoreGraphics content?

Say I have a UIView subclass called MyView that implements the drawRect: method like so:

- (void) drawRect: (CGRect) rect {
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(c, someColor);
    CGContextSetLineWidth(c, someWidth);
    CGContextMoveToPoint(c, leftOfMyUIView, topOfMyUIView);
    CGContextAddLineToPoint(c, leftOfMyUIView, bottomOfMyUIView);
    CGContextStrokePath(c);
}

In other words - it draws a vertical line down the left hand side of my subclass of UIView. Is there an easy way to now animate this UIView so that the line moves from the left side to the right side of the view? I would like it to 'drift' from left to right.

To be clear - for reasons I will not go into I cannot move/animate the instance of MyView. The best solution I can think of using is to add a new UIView subclass. Something like LineView extends UIView and then make LineView the exact dimensions of the line I want to draw, fill it using its own drawRect method and then add an instance of LineView to MyView as a subview. This would allow me to animate the position of the LineView object using an animation block, but seems overly complicated to achieve something so simple.

回答1:

Based upon your comment that there will be hundreds of LineView instances, it may be best to use CALayer subclasses as opposed to UIView subclasses. UIView objects give you event handling, and on iOS each UIView owns a CALayer to handle its rendering. If you don't want/need event tracking for the individual lines, all those UIView instances are probably needless overhead. You can access the parent UIView's layer, and add your line sublayers as needed.

If I understand your problem correctly, there should be no need for CoreGraphics. You can set the line layers' backgroundColor to handle the fill. Or if the lines will not be straight, you can use CAShapeLayer to render the paths of the lines.