IOS 图片折叠效果实现

来源:互联网 发布:淘宝邪气鞍座封号吗 编辑:程序博客网 时间:2024/04/29 16:32

当手指在图片中上下滑动的时候,图片的上半部分会有折叠效果。类似地可以扩展到其他需要折叠的场景中。

layer.contentsRect

用来截取layer的部分内容重新在frame中渲染。


代码及关键注释如下:

@interface ViewController ()


{

    /**

     *  创建两个UIImageView,分别用来保存图片的上、下两部分。

     */

    UIImageView *imageViewUp;

    UIImageView *imageViewDown;

}


@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    self.view.backgroundColor = [UIColorwhiteColor];

    // Do any additional setup after loading the view, typically from a nib.

    imageViewUp = [[UIImageViewalloc] initWithImage:[UIImageimageNamed:@"1"]];

    //设置折叠的锚点

    imageViewUp.layer.anchorPoint =CGPointMake(0.5,1);

    imageViewUp.frame =CGRectMake(10,100, 300, 150);

    //设置imageView的内容为图片的上半部分

    imageViewUp.layer.contentsRect =CGRectMake(0,0, 1,0.5);

    

    [self.viewaddSubview:imageViewUp];

    

    imageViewDown = [[UIImageViewalloc] initWithImage:[UIImageimageNamed:@"1"]];

    imageViewDown.layer.anchorPoint =CGPointMake(0.5,0);

    imageViewDown.frame =CGRectMake(10,250, 300, 150);

    imageViewDown.layer.contentsRect =CGRectMake(0,0.5, 1, 0.5);

    

    [self.viewaddSubview:imageViewDown];

    

    

    //添加一个透明浮层,用来捕捉手指滑动。

    UIView *clearView = [[UIViewalloc] initWithFrame:CGRectMake(10,100, 300, 300)];

    clearView.backgroundColor = [UIColorclearColor];

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizeralloc] initWithTarget:selfaction:@selector(pan:)];

    [clearView addGestureRecognizer:pan];

    clearView.userInteractionEnabled =YES;

    clearView.tag = 100;

    [self.viewaddSubview:clearView];


}


- (void)pan:(UIPanGestureRecognizer *)ges

{

    

    if (ges.state ==UIGestureRecognizerStateChanged) {

        UIView *clearView = (UIView *)[imageViewUpviewWithTag:100];

        CGPoint point = [ges translationInView:clearView];

        //计算旋转角度,拉动距离568时旋转90度。

        float R = -point.y*M_PI_2/568.0f;

        CATransform3D tran =CATransform3DIdentity;

        //设置折叠视角,使之更有立体感

        tran.m34 = -1.0/500.0;

        imageViewUp.layer.transform =CATransform3DRotate(tran, R, 1,0, 0);

    }

    elseif(ges.state ==UIGestureRecognizerStateEnded)

    {

        //当松开手指时,图片状态恢复。

        [UIView animateWithDuration:0.5fdelay:0.0foptions:UIViewAnimationOptionCurveLinearanimations:^{

            imageViewUp.layer.transform =CATransform3DIdentity;

        } completion:^(BOOL finished) {

            nil;

        }];

    }

}


0 0
原创粉丝点击