设置UISlider的ThumbImage,图片非常模糊, 使用代码生成图片就OK了

设置UISlider的ThumbImage,图片非常模糊, 使用代码生成图片就OK了

这样设置图片非常模糊:

[self.slider setThumbImage:[UIImage imageNamed:@"playDot"] forState:UIControlStateNormal];

 有锯齿:

  

正确的姿势:

UIImage *img = [OralTrainingHelper p_createImageWithColor:UIColorHex(#846FFD) andSize:CGSizeMake(16, 16)];
UIImage * resImg = [OralTrainingHelper p_generateCornerRadiusImage:img cornerRadius:8];
[self.slider setThumbImage:resImg forState:UIControlStateNormal];

效果如下:

两个工具类方法:

/// 纯色转图片
/// @param color 颜色
/// @param size 图片尺寸
+ (UIImage *)p_createImageWithColor:(UIColor *)color andSize:(CGSize)size {
    CGRect rect = CGRectMake(0.0, 0.0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultImage;
}

/// UIImage加圆角
/// @param image 图片
/// @param cornerRadius 圆角
+ (UIImage *)p_generateCornerRadiusImage:(UIImage *)original cornerRadius:(CGFloat)cornerRadius {
    UIGraphicsBeginImageContextWithOptions(original.size, NO, 0.0);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect rect = CGRectMake(0.0, 0.0, original.size.width, original.size.height);
    CGContextAddPath(ctx, [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius].CGPath);
    CGContextClip(ctx);
    [original drawInRect:rect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

 18年被这个问题困扰了好久,终于解决了

posted on 2022-02-28 11:26  土匪7  阅读(430)  评论(0)    收藏  举报