3

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.

Barjavel
  • 1,626
  • 3
  • 19
  • 31
  • Your update is pretty much the answer I was going to suggest when I first saw this question... drawRect isn't for animations, it is for drawing in a single point in time. You animate the properties of a view, in this case the `center`. Making your line a subview or sublayer (CAShapeLayer springs to mind for simplicity) and moving that is the only way to do it. – jrturton Jan 25 '12 at 14:13
  • The problem that I am working on will mean that I need to create many (hundereds) of these `LineView` instances. I won't be doing anything more complex than animating the position of each line. Given this context which of your two suggestions (`UIView` or `CALayer`) would be best suited? Is there much between them performance-wise? – Barjavel Jan 25 '12 at 14:36
  • CAShapeLayer would be best - you aren't creating a whole new view then, it is just a property of your view. – jrturton Jan 25 '12 at 14:46

1 Answers1

0

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.

TyR
  • 718
  • 4
  • 9