gpt4 book ai didi

ios - 自定义 UIButton 阴影

转载 作者:行者123 更新时间:2023-11-29 04:40:48 27 4
gpt4 key购买 nike

我有圆角矩形 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;

最佳答案

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

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

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

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

关于ios - 自定义 UIButton 阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10426692/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com