UIView设置阴影

 

UI设计师有时候希望我们的产品比较酷。

阴影是他们喜欢的效果之一。

 

怎么设置阴影呢?

 

1、设置一个四边都相同的阴影

   UIImageView *testImgView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 200, 100)];
    
    [testImgView setBackgroundColor:[UIColor yellowColor]];
    
    // 阴影颜色
    testImgView.layer.shadowColor = [UIColor blackColor].CGColor;
    // 阴影偏移,默认(0, -3)
    testImgView.layer.shadowOffset = CGSizeMake(0,0);
    // 阴影透明度,默认0
    testImgView.layer.shadowOpacity = 0.5;
    // 阴影半径,默认3
    testImgView.layer.shadowRadius = 5;
    
    [self.view addSubview:testImgView];
    

效果如图:

UIView设置阴影_第1张图片

 

2、设置单边阴影

 

//单边阴影
    
    UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 300, 200, 100)];
    
    [testLabel setBackgroundColor:[UIColor yellowColor]];
    
    // 阴影颜色
    testLabel.layer.shadowColor = [UIColor blackColor].CGColor;
    
    // 阴影偏移,默认(0, -3)
    testLabel.layer.shadowOffset = CGSizeMake(0,0);
    
    // 阴影透明度,默认0
    testLabel.layer.shadowOpacity = 0.5;
    // 阴影半径,默认3
    testLabel.layer.shadowRadius = 5;
    
    // 单边阴影 顶边
    float shadowPathWidth = testLabel.layer.shadowRadius;

    CGRect shadowRect = CGRectMake(-shadowPathWidth/2.0, 0-shadowPathWidth/2.0, testLabel.bounds.size.width+shadowPathWidth, shadowPathWidth);

    UIBezierPath *path = [UIBezierPath bezierPathWithRect:shadowRect];
    testLabel.layer.shadowPath = path.CGPath;
    
    [self.view addSubview:testLabel];

 

效果如下:

UIView设置阴影_第2张图片

 

3、和阴影相关的属性

 

/** Shadow properties. **/

/* The color of the shadow. Defaults to opaque black. Colors created
 * from patterns are currently NOT supported. Animatable. */

@property(nullable) CGColorRef shadowColor;

/* The opacity of the shadow. Defaults to 0. Specifying a value outside the
 * [0,1] range will give undefined results. Animatable. */

@property float shadowOpacity;

/* The shadow offset. Defaults to (0, -3). Animatable. */

@property CGSize shadowOffset;

/* The blur radius used to create the shadow. Defaults to 3. Animatable. */

@property CGFloat shadowRadius;

/* When non-null this path defines the outline used to construct the
 * layer's shadow instead of using the layer's composited alpha
 * channel. The path is rendered using the non-zero winding rule.
 * Specifying the path explicitly using this property will usually
 * improve rendering performance, as will sharing the same path
 * reference across multiple layers. Upon assignment the path is copied.
 * Defaults to null. Animatable. */

@property(nullable) CGPathRef shadowPath;

 

转载于:https://www.cnblogs.com/jukaiit/p/10940062.html

你可能感兴趣的:(ui)