UIView設置陰影

 

UI設計師有時候但願咱們的產品比較酷。ide

陰影是他們喜歡的效果之一。this

 

怎麼設置陰影呢?spa

 

一、設置一個四邊都相同的陰影

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

效果如圖:設計

 

二、設置單邊陰影

 

//單邊陰影
    
    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];

 

效果以下:code

 

三、和陰影相關的屬性

 

/** 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;
相關文章
相關標籤/搜索