这是我设置背景图片和内容模式的方法:
[btn setBackgroundImage:[UIImage imageNamed:@"dots_game_horiz_blue.png"]
forState:UIControlStateNormal];
[btn setContentMode:UIViewContentModeCenter];
背景图片变得像素化是有原因的吗?框架略大于图像尺寸,我只想让图像居中。
这是我设置背景图片和内容模式的方法:
[btn setBackgroundImage:[UIImage imageNamed:@"dots_game_horiz_blue.png"]
forState:UIControlStateNormal];
[btn setContentMode:UIViewContentModeCenter];
背景图片变得像素化是有原因的吗?框架略大于图像尺寸,我只想让图像居中。
我猜背景图片在 UIButton 中不被认为是“内容”,所以内容模式不适用于背景图片。相反,我设置了按钮的图像,它正常工作:
[btn setImage:[[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dots_game_horiz_blue" ofType:@"png"]] forState:UIControlStateNormal];
[btn setContentMode:UIViewContentModeCenter];
UIButton
类型设置为Custom
Image
属性中设置你的图像,而不是Background
Edge
属性的Image
选项以对按钮图像进行插图Top, Bottom, Left, Right
,则图像将位于按钮内部居中,周围有5个边框您可以在xib / storyboard视图中看到更改,无需启动调试。
提示:插图对于按钮的每个图像(State Config
)都是相同的。
您还可以实现- (CGRect)backgroundRectForBounds:(CGRect)bounds
方法来控制背景的绘制。
bounds
属性相关联,您可以在其中定义要绘制的背景矩形。- (CGRect)backgroundRectForBounds:(CGRect)bounds { UIImage *bkgImage = [self backgroundImageForState:self.state]; if (bkgImage) { CGFloat x = floorf((self.bounds.size.width-bkgImage.size.width)/2); CGFloat y = floorf((self.bounds.size.height-bkgImage.size.height)/2); return CGRectMake(x, y, bkgImage.size.width, bkgImage.size.height); } else return [super backgroundRectForBounds:bounds]; }
- José Manuel Sánchez我需要为头像照片创建圆形按钮,并找到了这个问题的答案来帮助我,但它们并没有完全解决我的问题。我实现了backgroundRectForBounds
方法并缩放图像以适应,效果很好。
我已经将代码上传至GitHub。
https://github.com/brennanMKE/CircleButton
该方法如下所示。重要的是设置背景图像而不是按钮图像,因为该方法无法使用按钮图像。
- (CGRect)backgroundRectForBounds:(CGRect)bounds {
UIImage *backgroundImage = [self backgroundImageForState:self.state];
if (backgroundImage) {
CGFloat maxWidth = CGRectGetWidth(self.frame);
CGFloat xDelta = maxWidth / backgroundImage.size.width;
CGFloat yDelta = maxWidth / backgroundImage.size.height;
CGFloat delta = xDelta > yDelta ? xDelta : yDelta;
CGFloat x = floorf((self.bounds.size.width - (backgroundImage.size.width * delta)) / 2);
CGFloat y = floorf((self.bounds.size.height - (backgroundImage.size.height * delta)) / 2);
return CGRectMake(x, y, backgroundImage.size.width * delta, backgroundImage.size.height * delta);
}
else {
return [super backgroundRectForBounds:bounds];
}
}