【问题标题】:Is there a way to change the color of an image without losing the pattern on it有没有办法在不丢失图案的情况下改变图像的颜色
【发布时间】:2023-03-10 11:52:01
【问题描述】:

有没有办法在不丢失图案的情况下改变图像的颜色?

【问题讨论】:

    标签: iphone objective-c ipad


    【解决方案1】:

    试试这个(UIImage 类别):

    .h

    @interface UIImage (Overlay)
    
    - (UIImage *)imageWithOverlayColor:(UIColor *)color;
    
    @end
    

    .m

    #import "UIImage+Overlay.h"
    
    @implementation UIImage (Overlay)
    
    - (UIImage *)imageWithOverlayColor:(UIColor *)color
    {        
        CGRect rect = CGRectMake(0.0f, 0.0f, self.size.width, self.size.height);
    
        if (UIGraphicsBeginImageContextWithOptions) {
            CGFloat imageScale = 1.0f;
            if ([self respondsToSelector:@selector(scale)])  // The scale property is new with iOS4.
                imageScale = self.scale;
            UIGraphicsBeginImageContextWithOptions(self.size, NO, imageScale);
        }
        else {
            UIGraphicsBeginImageContext(self.size);
        }
    
    //    [self drawInRect:rect];
    
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextTranslateCTM(context, 0, self.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
    
        CGContextSetBlendMode(context, kCGBlendModeMultiply);
           CGContextDrawImage(context, rect, self.CGImage);
        CGContextSetFillColorWithColor(context, color.CGColor);
        CGContextClipToMask(context, rect, self.CGImage);
        CGContextFillRect(context, rect);   
    
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return image;
    }
    
    @end
    

    这样称呼它:

    UIImage *image = [UIImage imageNamed:@"image.png"]; 
    image = [image imageWithOverlayColor:[UIColor redColor]];
    

    前后图片:

    【讨论】:

    • 如果您不喜欢这个结果,您可以尝试不同的混合模式。
    • 当用户更改图像的颜色时,我调用此方法: UIImage *coloreImage = [self imageWithOverlayColor:color]; subLayer.contents = (id) coloreImage.CGImage;我将返回图像提供给 CGLayer。即使结果相同,我也尝试过不同的混合模式。
    • 您是否将其用作类别,并且您的图像是否从一开始就包含图像?这个对我有用。示例:UIImage *image = [UIImage imageNamed:@"image.png"]; image = [image imageWithOverlayColor:[UIColor redColor]];
    • 它现在正在改变图像的颜色,但我失去了它的图案。如何在不影响图案的情况下更改图像颜色?
    • 查看我的更新实现。请注意,当然,如果要保留边缘,图像需要是透明的 png 或 gif。
    猜你喜欢
    • 2017-12-24
    • 2019-11-03
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 2023-03-21
    • 2021-09-24
    • 2011-04-07
    • 2017-07-05
    相关资源
    最近更新 更多