3

我有一个按钮的背景图像,尺寸为 80x30 像素。

我使用下面的代码在我的视图控制器中设置背景,结果是这样的:

顶部和角落很吵

如您所见,右侧按钮的角和顶部被弄乱了。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    UIImage *favoriteBtnImgNormal = [[UIImage imageNamed:@"favorite-btn-normal"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 30, 30, 0)];
    UIImage *favoriteBtnImgTouch = [[UIImage imageNamed:@"favorite-btn-touch"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 30, 30, 0)];

    [self.navigationItem.rightBarButtonItem setBackgroundImage:favoriteBtnImgNormal forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [self.navigationItem.rightBarButtonItem setBackgroundImage:favoriteBtnImgTouch forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
    [self.navigationItem.rightBarButtonItem setBackgroundImage:favoriteBtnImgTouch forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
    [self.navigationItem.rightBarButtonItem setTitlePositionAdjustment:UIOffsetMake(-10.0, 0.0) forBarMetrics:UIBarMetricsDefault];
}

请注意,我在单个视图控制器中执行此操作,我使用外观 API 来设置一般样式。但在这里我想覆盖一般外观。

如果我只得到没有可调整大小的图像,它看起来像这样:

太大了

现在边缘和角落都很好,但是按钮太大了。

我确定我做错了,所以我需要有人指出我可以做些什么来正确缩放按钮?

4

1 回答 1

0
UIImage *image = [UIImage imageNamed:@"YourImage"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

button.bounds = CGRectMake( 0, 0, image.size.width, image.size.height );

[button setImage:image forState:UIControlStateNormal];
[button addTarget:self action:@selector(YourAction) forControlEvents:UIControlEventTouchUpInside];

button.contentEdgeInsets = (UIEdgeInsets){.right=-10};

self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:button] autorelease];
于 2013-04-03T03:34:41.187 回答