How to prevent bold images with UIImageRenderingModeAlwaysTemplate

后端 未结 4 1914
野性不改
野性不改 2020-12-31 19:30

My application has a toolbar with image buttons on them (subclass of UIButton); when the user switches on the \"Bold text\" accessibility option, not only the text becomes b

4条回答
  •  庸人自扰
    2020-12-31 19:40

    Thanks to Rufel's answer I was able to fix my issue and reduce the code of my class at the same time:

    #import "AppButton.h"
    
    @interface AppButton ()
    
    @property (readonly) UIImage *normalImage;
    
    @end
    
    @implementation AppButton
    
    @synthesize highlightTintColor = _highlightTintColor;
    
    - (id)initWithCoder:(NSCoder *)aDecoder
    {
        if (self = [super initWithCoder:aDecoder]) {
            [self initialize];
        }
        return self;
    }
    
    - (UIImage *)normalImage
    {
        return [self imageForState:UIControlStateNormal];
    }
    
    - (void)initialize
    {
        self.adjustsImageWhenHighlighted = NO;
        // set disabled image
        [self setImage:[self image:self.normalImage tintedWithColor:[UIColor colorWithRGBValue:RGBValueC9]] forState:UIControlStateDisabled];
    }
    
    - (void)setHighlightTintColor:(UIColor *)highlightTintColor
    {
        _highlightTintColor = highlightTintColor;
        // update highlighted image
        if (highlightTintColor) {
            [self setImage:[self image:self.normalImage tintedWithColor:highlightTintColor] forState:UIControlStateHighlighted];
        }
    }
    
    - (UIImage *)image:(UIImage *)image tintedWithColor:(UIColor *)tintColor
    {
        CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
        UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0f);
    
        // Tint image
        [tintColor set];
        UIRectFill(rect);
        [image drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1.0f];
        UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return tintedImage;
    }
    
    @end
    

提交回复
热议问题