iOS 栏目图像显示错误的颜色

iOS Bar Item image displaying wrong color

我有一个带有条形项的条形图,我的 .png 图像是绿色的,但是当我将它添加到故事板时它显示为蓝色。

如何让它按原样显示图像?

The docs 对此有点模棱两可

The images displayed on the bar are derived from this image. If this image is too large to fit on the bar, it is scaled to fit. Typically, the size of a toolbar and navigation bar image is 20 x 20 points. The alpha values in the source image are used to create the images—opaque values are ignored.

基本上这就是说您提供的图像不会是实际显示的图像。相反,系统使用图像的 alpha 掩码和项目的 tintColor 来生成最终显示。

使用 UIBarButton 的 tintColor 设置图像所需的颜色。 如果绝对需要使用原始图像颜色,请使用此设置图像:

[aBarButton setImage:[[UIImage imageNamed:@"xyz.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

要设置全局栏项目的色调,在您的 App Delegate 中,添加这些代码行

UIBarButtonItem *barButtonAppearance = [UIBarButtonItem appearance];
[barButtonAppearance setTintColor:[UIColor redColor]]; // set to your color
[[UIBarButtonItem appearance] setTintColor:[UIColor redColor]];

您必须设置 UITabBar tintColor。

如果您想添加自定义颜色/渐变,您可以按如下方式设置 tabBarItem 图像和 selectedImage 属性:

 customTabBarItem.selectedImage = UIImage(named: "customSelectedImage")!.imageWithRenderingMode(.AlwaysOriginal)
 customTabBarItem.image = UIImage(named: "customUnselectedImage")!.imageWithRenderingMode(.AlwaysOriginal)

以编程方式添加图像

[button setImage:[[UIImage imageNamed:@"imageName.png"]   imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]     forState:UIControlStateNormal];

如果它不起作用,那么试试这个:-

UIImage *myImage = [UIImage imageNamed:@"myImageFile.png"];
myImage = [myImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithImage:myImage   style:UIBarButtonItemStylePlain target:self action:@selector(menuObject:)];
self.navigationItem.leftBarButtonItem = menuButton;

如果它不起作用,那么试试这个:-

#define setTurqoiseColor [UIColor colorWithRed:68.0f/255.0f green:181.0f/255.0f blue:223.0f/255.0f alpha:1.0]

UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithImage:buttonImage style:UIBarButtonItemStyleBordered target:self  action:@selector(toggleMenu)];
menuButton.tintColor = setTurqoiseColor;