我正在开发一个应用程序,其中元素需要以不同的颜色进行自定义。到目前为止,我一直在利用tintColor
和imageWithRenderingMode
来更改图片颜色。我目前处于需要使用UIColor(patternImage:)
和backgroundColor
添加背景图块图像的情况。有没有办法将一种色调应用于背景图块图像,以便我可以在运行时更改背景图像颜色?
答案 0 :(得分:1)
您可以将TintColor应用于UIImage并使用该UIImage作为平铺的背景颜色。
将tintColor应用于UIImage:
- (UIImage *) addOverlaytoImage:(UIImage *)mySourceImage
{
UIImage * image = mySourceImage;
UIColor * color = [UIColor yellowColor];
UIGraphicsBeginImageContext(image.size);
[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height) blendMode:kCGBlendModeNormal alpha:1];
UIBezierPath * path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, image.size.width, image.size.height)];
[color setFill];
[path fillWithBlendMode:kCGBlendModeMultiply alpha:1]; //look up blending modes for your needs
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
然后将此图像添加到背景颜色参数:
yourView.backgroundColor = [UIColor colorWithPatternImage:[self addOverlaytoImage:myImage]];
答案 1 :(得分:0)
通过我找到here的链接,这就是我的工作原理
// originalImage and originalColor are defined
var image = originalImage.imageWithRenderingMode(.AlwaysTemplate)
UIGraphicsBeginImageContextWithOptions(
originalImage.size,
false,
originalImage.scale)
originalColor.set()
image.drawInRect(CGRectMake(
0,
0,
originalImage.size.width,
originalImage.size.height))
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return UIColor(patternImage: image)
答案 2 :(得分:0)
J_P,谢谢您的回答!真的很有帮助。我只想发布Swift 5的更新版本
extension UIColor {
convenience init(patternImage: UIImage, tintColor: UIColor) {
var image = patternImage.withRenderingMode(.alwaysTemplate)
UIGraphicsBeginImageContextWithOptions(patternImage.size,
false,
patternImage.scale)
tintColor.set()
image.draw(in: CGRect(x: 0, y: 0,
width: patternImage.size.width,
height: patternImage.size.height))
image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.init(patternImage: image)
}
}