欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

UIView设置阴影

程序员文章站 2022-06-19 18:25:37
UI设计师有时候希望我们的产品比较酷。 阴影是他们喜欢的效果之一。 怎么设置阴影呢? 1、设置一个四边都相同的阴影 效果如图: 2、设置单边阴影 效果如下: 3、和阴影相关的属性 ......

 

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设置阴影

 

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设置阴影

 

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;