Search code examples
iphoneioscore-animationcalayeruigesturerecognizer

Is it good choice to move a Sublayer around a view using UIPanGestureRecognizer?


I have a CALayer and as sublayer to this CALayer i have added an imageLayer which contains an image of resolution 276x183.

I added a UIPanGestureRecognizer to the main view and calculation the coordinates of the CALayer as follows:

- (void)panned:(UIPanGestureRecognizer *)sender{

        subLayer.frame=CGRectMake([sender locationInView:self.view].x-138, [sender locationInView:self.view].y-92, 276, 183);

}

in viedDidLoad i have:

subLayer.backgroundColor=[UIColor whiteColor].CGColor;
subLayer.frame=CGRectMake(22, 33, 276, 183);

imageLayer.contents=(id)[UIImage imageNamed:@"A.jpg"].CGImage;
imageLayer.frame=subLayer.bounds;
imageLayer.masksToBounds=YES;
imageLayer.cornerRadius=15.0;

subLayer.shadowColor=[UIColor blackColor].CGColor;
subLayer.cornerRadius=15.0;
subLayer.shadowOpacity=0.8;
subLayer.shadowOffset=CGSizeMake(0, 3);
[subLayer addSublayer:imageLayer];
[self.view.layer addSublayer:subLayer];

It is giving desired output but a bit slow in the simulator. I have not yet tested it in Device. so my question is - Is it OK to move a CALayer containing an image??


Solution

  • Two things:

    First, you can't draw ANY conclusions based on the performance of the simulator. Some things on the simulator are an order of magnitude faster than on a device, and other things are significantly slower. Animation is especially a mixed bag.

    If you're doing performance-critical work, test it on the device, early and often.

    Second, you can certainly animate a layer using a gesture recognizer, but that is an awfully round-about way to do it. Gesture recognizers are designed to work on views, and it's much easier and cleaner to tie the recognizer to a subview rather than a sub layer.

    One of the big problems you will have with using a layer is hit-testing. If you let go of your image, then try to drag it some more, you'll have to have the gesture on the containing view, take the gesture coordinates and do hit testing on the layer. Ugh.

    Take a look at the gesture based version of the touches sample app from Apple. It shows you how to cleanly move UIView objects around the screen using gestures.

    Note that you can create a view that has custom layer content, and drag that around.