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

效果如圖:

 

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

 

效果如下:

 

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;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM