图像和背景图像的UIButton
问题描述:
我有一个图像是480x331,并有一个透明的背景。透明部分就在图像边缘附近。我的UIButton是72x37。当我在IB中将图像设置为背景图像时,图像的透明边缘在按钮中显示为白色。没有图像,按钮是白色的圆角。我猜这是我看到的白色。如果是这样,这意味着图像透明度正在工作,但按钮的白色区域正在显示。图像和背景图像的UIButton
如果我将图像设置为UIButton的Image属性,即使在更改视图模式之后,它仍然无法正确缩放,并保持其全尺寸。
任何建议,我应该使用哪些属性来扩展和透明度的工作权利?
答
你正在使用什么按钮类型?
通过它的声音,你可能使用UIButtonTypeRoundedRect风格,但UIButtonTypeCustom可能更合适。您可以在Interface Builder的检查器窗口中更改它。
答
@Christopher Fairbaim建议使用UIButtonTypeCustom。使用UIButtonTypeRoundedRect将为您提供透明区域中的白色背景。
但是,在Interface Builder中进行接线有其局限性。如果您想从数据集或基于用户输入动态生成UIViews,UIButtons和资产,可以通过编程方式进行操作。
创建的按钮:(注:这也将与其他UIButtonTypes工作,但我用UIButtonTypeCustom这个特定透明度的例子。)
UIButton *btnName = [UIButton buttonWithType:UIButtonTypeCustom];
要更改所需的属性:
btnName.backgroundColor = [UIColor clearColor];
btnName.frame = CGRectMake(100, 100, 72, 37); //(X coord, Y coord, width, height)
[btnName addTarget:myActionClassName action:@selector(myActionName) forControlEvents:UIControlEventTouchUpInside];
要为各种状态添加图像(假设这些都是透明的PNG的):
UIImage *btnNameImageNormal = [UIImage imageNamed:@"btnNameNormal.png"];
[btnName setBackgroundImage:btnMenuImageNormal forState:UIControlStateNormal];
UIImage *btnNameImagePressed = [UIImage imageNamed:@"btnNamePressed.png"];
[btnName setBackgroundImage:btnNameImagePressed forState:UIControlStateHighlighted];
要将按钮添加到图(从的viewController类中):
[self addSubview:btnName];
(赦免任何错别字,因为我复制并从我的一个项目粘贴,并试图推广的命名。)