IOS - 图形凹凸变化

一个简单的图片凹凸,可以让UI有很大的变化。

演示图

图片的变形,就是一个贝塞尔曲线(UIBezierPath)的简单应用。


#define ScreenW self.view.frame.size.width
#define ScreenH self.view.frame.size.height

#define MoveY 50.0


/**
 *  创建界面
 */
-(void)createView
{
    UIScrollView *scroll = [[UIScrollView alloc] init];
    scroll.delegate = self;
    scroll.frame = self.view.bounds;
    scroll.contentSize = CGSizeMake(ScreenW, ScreenH+MoveY*2);
    [self.view addSubview:scroll];
    
    UIImageView *imgView = [[UIImageView alloc] init];
    imgView.image = [UIImage imageNamed:@"pic"];
    imgView.frame = CGRectMake(0, 0, ScreenW, ScreenW);
    [scroll addSubview:imgView];
    
    UIView *shapeView = [[UIView alloc] init];
    shapeView.frame = CGRectMake(0, ScreenW-MoveY*2, ScreenW, ScreenH-ScreenW);
    [scroll addSubview:shapeView];
    
    //变形图层
    CAShapeLayer *shapeLayer = [[CAShapeLayer alloc] init];
    shapeLayer.fillColor = [UIColor whiteColor].CGColor;
    [shapeView.layer addSublayer:shapeLayer];
    self.iLayer = shapeLayer;
    
    [self changeRect:MoveY withY:0];
}

/**
 *  UIScrollView 代理方法
 *
 *  @param scrollView
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    float curY = scrollView.contentOffset.y;
    if (curY > 0 && curY < MoveY) {
        [self changeRect:fabs(MoveY - curY) withY:curY];
    }else if(curY <= 0){
        [self changeRect:MoveY withY:curY];
    }else if(curY >= MoveY){
        [self changeRect:0 withY:curY];
    }
}


/**
 *  根据Y值,内容界面凹凸
 *
 *  @param changeY
 */
-(void)changeRect:(float)changeY withY:(float)setY
{
    //边 凹凸
    CGSize size = CGSizeMake(ScreenW, ScreenH-ScreenW);
    float layerH = changeY;
    UIBezierPath *path = [[UIBezierPath alloc] init];
    [path moveToPoint:CGPointMake(0, 0)];
    [path addLineToPoint:CGPointMake(0, size.height)];
    [path addLineToPoint:CGPointMake(size.width, size.height)];
    [path addLineToPoint:CGPointMake(size.width, 0)];
    [path addQuadCurveToPoint:CGPointMake(0,0) controlPoint:CGPointMake(size.width / 2, layerH)];
    self.iLayer.path = path.CGPath;
}

这此基础上,还可以再增加更多的UI变化,这里只是关键的代码。

你可能感兴趣的:(IOS - 图形凹凸变化)