【问题标题】:Changing UIColor of the buttonImage更改 buttonImage 的 UIColor
【发布时间】:2015-11-17 10:17:17
【问题描述】:

我有一个UIImageredColor 但我想在whiteColor 中显示它,怎么做?这是我的代码:

UIImage *buttonImage = [UIImage imageNamed:@"close-button.png"];
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
aButton.frame = CGRectMake(0.0,
                           0.0, 
                           buttonImage.size.width,
                           buttonImage.size.height);

UIBarButtonItem *aBarButtonItem = 
  [[UIBarButtonItem alloc] initWithCustomView:aButton];

[aButton addTarget:self action:@selector(didSelectBackButton:) 
               forControlEvents:UIControlEventTouchUpInside];

[self.navigationItem setLeftBarButtonItem:aBarButtonItem];

【问题讨论】:

  • 您的问题不清楚,当您需要将按钮颜色更改为白色时,如果正常否则用户点击当时的事件
  • 默认颜色应为白色。
  • 你可以设置uiimage和背景颜色为红色吗?

标签: ios objective-c uibutton uiimage uicolor


【解决方案1】:

如果您想更改UIImageUIColor,请在UIImageinterface 中使用此方法:

- (UIImage *)imageWithColor:(UIColor *)color
{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, self.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextClipToMask(context, rect, self.CGImage);
    [color setFill];
    CGContextFillRect(context, rect);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

【讨论】:

    【解决方案2】:

    试试这个:

    UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 150, 40)];
    UIImage *img = [UIImage imageNamed:imageName];
    icon.image = [img imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    icon.tintColor = tintColor;
    icon.contentMode = UIViewContentModeScaleAspectFill;
    

    【讨论】:

    • 我试过了,但它不起作用,图像仍然是红色的,我在调试视图中检查了它。我的导航栏是红色的,我的图像也是红色的,这就是我希望关闭按钮为白色的原因。
    • 您是否尝试更改导航栏的tintColor
    【解决方案3】:

    只需使用renderingMode添加图像,然后设置色调。 此外,您不希望使用淡色渲染的图像的背景和任何部分都必须完全透明。

    https://www.captechconsulting.com/blogs/ios-7-tutorial-series-tint-color-and-easy-app-theming

    UIImage *buttonImage = [[UIImage imageNamed:@"close-button.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    
    [aButton setTintColor:[UIColor whiteColor]];
    

    【讨论】:

      猜你喜欢
      • 2020-10-04
      • 1970-01-01
      • 2019-08-01
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多