问题
I have to imagine this has been asked several times, but I must not be wording my question correctly.
I have my own custom image I made in photoshop and it is set as a button's image property. Here it is showing normally:
The background is transparent, but it is 44x44 with the three dots being a 88x88 pixel .png file. So if I do something like this:
self.theButton.tintColor = [UIColor redColor];
the image still shows as white. I am not a designer by trade, so I seem to be missing how to properly save or set up the files to make them respect the tintColor property. In photoshop, I usually save these using "Save for web".
Thanks
回答1:
What you are looking for are stencil images.
From the UIKit User Interface Catalog:
Template Images
In iOS 7, you can choose to treat any of the images in your app as a template—or stencil—image. When you elect to treat an image as a template, the system ignores the image’s color information and creates an image stencil based on the alpha values in the image (parts of the image with an alpha value of less than 1.0 get treated as completely transparent). This stencil can then be recolored using tintColor to match the rest of your user interface.
By default, an image (UIImage) is created with UIImageRenderingModeAutomatic. If you have UIImageRenderingModeAutomatic set on your image, it will be treated as template or original based on its context. Certain UIKit elements—including navigation bars, tab bars, toolbars, segmented controls—automatically treat their foreground images as templates, although their background images are treated as original. Other elements—such as image views and web views—treat their images as originals. If you want your image to always be treated as a template regardless of context, set UIImageRenderingModeAlwaysTemplate; if you want your image to always be treated as original, set UIImageRenderingModeAlwaysOriginal.
To specify the rendering mode of an image, first create a standard image, and then call the imageWithRenderingMode: method on that image.
UIImage *myImage = [UIImage imageNamed:@"myImageFile.png"]; myImage = [myImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
回答2:
You might achieve the result you want by using a UIImage with rendering mode UIImageRenderingModeAlwaysTemplate.
UIImage *image = [UIImage imageNamed:@"Dots"];
UIImage *templateImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[theButton setImage:templateImage forState:UIControlStateNormal];
回答3:
Their are two way to set template image
1.Using Images.assets
2.Using Code
UIImage *myImage = [UIImage imageNamed:@"myImageFile.png"];
myImage = [myImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
imageView.image = myImage;
imageView.tintColor = [UIColor greenColor] // or any other color you want
来源:https://stackoverflow.com/questions/20891491/make-custom-image-respect-tintcolor-property-ios