How to prevent bold images with UIImageRenderingModeAlwaysTemplate

后端 未结 4 1896
野性不改
野性不改 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:56

    I recommend you to use a custom category to tint your image buttons. Here is a simple implementation that does just that:

    UIImage+TintImage.h

    @interface UIImage (TintImage)
    - (UIImage *)imageTintedWithColor:(UIColor *)tintColor;
    @end
    

    UIImage+TintImage.m

    #import "UIImage+TintImage.h"
    
    @implementation UIImage (TintImage)
    - (UIImage *)imageTintedWithColor:(UIColor *)tintColor
    {
        if (tintColor == nil) {
            tintColor = [UIColor whiteColor];
        }
    
        CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
        UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
    
        // Tint image
        [tintColor set];
        UIRectFill(rect);
        [self drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1.0f];
        UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return tintedImage;
    }
    @end
    

    To use it, just import "UIImage+TintImage.h", then do the following:

    UIImage *originalImage = [UIImage imageNamed:@"icn-menu"];
    UIImage *tintedImage = [originalImage imageTintedWithColor:[UIColor blueColor]];
    UIButton *homeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [homeButton setImage:originalImage forState:UIControlStateNormal];
    [homeButton setImage:tintedImage forState:UIControlStateHighlighted];
    

    button showcase

提交回复
热议问题