我有一个透明的图像("hold_empty.png",下面),我想把它变成一个按钮。在按钮内,将有一个带有彩色背景的视图,其大小略小于实际图像,以保持背景色。
原因是因为图像有圆角,所以我不能简单地将背景颜色放在图像上,因为它看起来比图像要大。

这张图片是一个透明的正方形,带有“圆角”。我试图创造的效果应该是层次分明的。
我正在经历的问题是,只有图像(及其边界)看起来是可点击的,而不是整个对象。
代码如下所示。
// x,y,w,h
CGRect frame = CGRectMake(10, 10, 72, 72);
CGRect frame2 = CGRectMake(5, 5, 60, 60); // I know this is not filling the image, its just a test
UIView *bgColorView = [[UIView alloc] initWithFrame:frame2];
[bgColorView setFrame:frame2];
bgColorView.backgroundColor = [UIColor redColor];
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"hold_empty" ofType:@"png"]];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addSubview:bgColorView];
[btn setImage:image forState:UIControlStateNormal];
btn.frame = frame;
[btn addTarget:self action:@selector(btnSelectColor:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
[bgColorView release];因此,总结一下:如何使透明的图像按钮具有可点击的背景颜色?
谢谢。
发布于 2011-01-04 14:56:42
我现在已经破解了。我遇到的问题之一是,它没有与化身一起工作(有时它会出现在图层后面,而另一些时候则根本不会显示出来)。
这是我的解决方案。
UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"some_avatar" ofType:@"png"]];
UIImageView *imgView = [[UIImageView alloc] initWithImage:image];
CGRect fullFrame = CGRectMake(25, 10, 70,72);
CGRect frame = CGRectMake(28, 13, 63,65);
UIButton *h=[UIButton buttonWithType:UIButtonTypeCustom];
[h setFrame:fullFrame];
[[h layer] setMasksToBounds:YES];
//[h setBackgroundImage:image forState:UIControlStateNormal];
//[h setImage:image forState:UIControlStateNormal];
[h setShowsTouchWhenHighlighted:YES];
[h setClipsToBounds:YES];
CAGradientLayer *gradientLayer = [[CAGradientLayer alloc] init];
[gradientLayer setBounds:frame];
[gradientLayer setPosition:CGPointMake([h bounds].size.width/2, [h bounds].size.height/2)];
[gradientLayer setColors:[NSArray arrayWithObjects:
(id)[[UIColor darkGrayColor]CGColor],(id)[[UIColor blackColor] CGColor], nil]];
[[h layer] insertSublayer:gradientLayer atIndex:0];
[h insertSubview:imgView atIndex:1];
[h addTarget:self action:@selector(btnSelectColor:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:h];
[imgView release];发布于 2011-01-01 16:09:12
可点击区域通常是按钮的frame,如果你允许它们剪辑内容的话,它不会被它的超级视图剪裁。
事实上,你在屏幕上看到的东西并不意味着它在你可以触摸的意义上是“可见的”。如果您让每个视图剪辑它的子视图(通过IB,或通过设置view.clipsToBounds = YES;),那么在这方面的任何问题都会清楚地显示出来。
(请注意,任何UIButton、UIImageView等都是view,可以设置为剪辑其内容)
发布于 2011-01-02 00:05:20
您需要在子视图上启用用户交互吗?
bgColorView.userInteractionEnabled = YES;https://stackoverflow.com/questions/4574586
复制相似问题