我正在开发一款游戏,出于某种原因,边框粗细会根据按钮的颜色而变化。直到我在应用程序上放置背景图片后才出现此问题,所以我不确定是什么原因造成的。我拍了几张截图来说明我的意思。出于某种原因,当带边框的按钮为蓝色时,边框粗细变为 2px 而不是 1px。
此外,控制按钮的边框也存在一些问题。我所说的控制按钮是指顶部的 6 个按钮,顺序为红色、蓝色、棕色、绿色、紫色和黄色。
截图如下:
我通过在背景中放置一个按钮来创建边框,该按钮从 x-1,y-1 开始,宽度为 width+2,高度为 height+2。这里有一段代码可以给你一个想法:
UIButton *borderButton = [UIButton buttonWithType:UIButtonTypeCustom];
borderButton.frame = CGRectMake((controlX-1), (controlY-1), 42, 32);
borderButton.backgroundColor = [UIColor blackColor];
[self.view addSubview:borderButton];
UIButton *controlButton = [UIButton buttonWithType:UIButtonTypeCustom];
[controlButton addTarget:self
action:@selector(doMove:)
forControlEvents:UIControlEventTouchDown];
controlButton.frame = CGRectMake(controlX, controlY, 40, 30);
controlButton.tag = 500 + i;
tmpColor = [self.colors objectAtIndex:i];
controlButton.backgroundColor = tmpColor;
[self.view addSubview:controlButton];
这段代码取自一个循环,其中 controlX 和 controlY 给出了控制按钮应该从哪里开始的 x/y 值。
如果有人知道如何解决这个问题,我将不胜感激。如果我以错误的方式处理边界,并且有一种更简单且问题更少的方法来实现相同的外观,我也愿意这样做,因为我这边不会有太多代码需要更改。提前感谢任何可以帮助我解决这个恼人的 UI 故障的人。
最佳答案
实现带边框的自定义按钮最简单的方法是使用按钮层:
#import <QuartzCore/QuartzCore.h>
...
UIButton *controlButton = [UIButton buttonWithType:UIButtonTypeCustom];
[controlButton addTarget:self
action:@selector(doMove:)
forControlEvents:UIControlEventTouchDown];
controlButton.frame = CGRectMake(controlX, controlY, 40, 30);
controlButton.tag = 500 + i;
// Set layer properties
controlButton.layer.borderWidth = 1.0;
controlButton.layer.borderColor = [UIColor blackColor].CGColor;
controlButton.layer.cornerRadius = 5.0; // if you want rounded corners...
tmpColor = [self.colors objectAtIndex:i];
controlButton.backgroundColor = tmpColor;
[self.view addSubview:controlButton];
您可能还需要检查按钮和其他元素(如标签)是否位于整数坐标处以避免图像模糊。要更正坐标,请使用 CGRectIntegral
附言对于复杂的动画/游戏逻辑,最好使用像 Cocos2D 这样的框架。
关于objective-c - 为什么边框粗细会随着按钮的颜色而变化(蓝色边框为 2px)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13796563/