1

我有一个 CALayer,作为这个 CALayer 的子层,我添加了一个 imageLayer,其中包含分辨率为 276x183 的图像。

我在主视图中添加了一个 UIPanGestureRecognizer 并计算 CALayer 的坐标如下:

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

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

}

在 viedDidLoad 我有:

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];

它提供了所需的输出,但在模拟器中有点慢。我还没有在设备中测试过它。所以我的问题是 - 移动包含图像的 CALayer 可以吗?

4

2 回答 2

2

是的,可以移动包含图像的 CALayer。

如果您想要对平移手势做的只是移动图像,那么frame您应该只更新图层的position属性,而不是更新整体。像这样:

- (void)panned:(UIPanGestureRecognizer *)sender {
    subLayer.position=CGPointMake([sender locationInView:self.view].x, [sender locationInView:self.view].y);
}
于 2012-09-04T15:36:30.950 回答
1

两件事情:

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.

于 2012-09-06T12:15:40.417 回答