【问题标题】:custom UIButton shadow自定义 UIButton 阴影
【发布时间】:2012-05-03 07:08:09
【问题描述】:

我有圆角矩形 UIButton 并想为其添加阴影,但是当我设置背景图像阴影不可见时,我认为背景会覆盖阴影。没有背景图像阴影可见

customBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    customBtn.frame=CGRectMake(customBtn.frame.origin.x, customBtn.frame.origin.y, 30, 30);
     [customBtn setImage:[UIImage imageNamed:@"icon.png"] forState:UIControlStateNormal];
     [customBtn setBackgroundImage:[[UIImage imageNamed:@"bg.png"] stretchableImageWithLeftCapWidth:0 topCapHeight:0] forState:UIControlStateNormal];
    customBtn.layer.cornerRadius=9;

 customBtn.layer.shadowColor = [UIColor redColor].CGColor;
    customBtn.layer.shadowOpacity = 1.0;
    customBtn.layer.shadowRadius = 1;
    customBtn.layer.shadowOffset = CGSizeMake(2.0f, 2.0f);
customBtn.clipsToBounds=YES;

【问题讨论】:

  • 尝试删除 clipToBounds=YES(或将其设置为 NO)

标签: ios cocoa-touch uibutton calayer


【解决方案1】:

由于UIButton 的内部结构,最好的办法是创建一个包含阴影的可拉伸背景图像。

UIImage *bgWithShadow = [[UIImage imageNamed: @"bg.png"] 
                            stretchableImageWithLeftCapWidth: 10 
                                                topCapHeight: 0];
[customBtn setBackgroundImage: bgWithShadow 
                     forState: UIControlStateNormal];

此示例假定bg.png 是一个包含阴影的 21 像素宽的图像。基本上,您无需执行任何其他操作,例如访问按钮的层或更改其clipsToBounds 属性。请参阅this question 了解什么是可拉伸图像(带有图片!)。

请注意,stretchableImageWithLeftCapWidth:topCapHeight: 已被弃用,取而代之的是 resizableImageWithCapInsets:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多