作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想为可拉伸(stretch)的 UIImage 着色,但无法使其工作。在这篇文章的帮助下:How to change the color of an UIImage我已成功为 UIImage 着色,但当我使其可拉伸(stretch)时,颜色未设置在"new"框架上。
以下是我如何使用类别设置颜色:
+ (UIImage *)imageNamed:(NSString *)name withColor:(UIColor *)color
{
UIImage *image = [UIImage imageNamed:name];
if (color == nil)
return image;
CGRect rect = CGRectMake(0.f, 0.f, image.size.width, image.size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClipToMask(context, rect, image.CGImage);
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return [UIImage imageWithCGImage:img.CGImage
scale:1.0
orientation:UIImageOrientationDownMirrored];
}
如有任何建议,我们将不胜感激...
最佳答案
这段代码应该可以工作:
+ (UIImage *)imageNamed:(NSString *)name withColor:(UIColor *)theColor
{
UIImage *baseImage = [UIImage imageNamed:name];
UIGraphicsBeginImageContext(baseImage.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(0, 0, baseImage.size.width, baseImage.size.height);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -area.size.height);
CGContextSaveGState(ctx);
CGContextClipToMask(ctx, area, baseImage.CGImage);
[theColor set];
CGContextFillRect(ctx, area);
CGContextRestoreGState(ctx);
CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
CGContextDrawImage(ctx, area, baseImage.CGImage);
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
关于iphone - 如何为可拉伸(stretch)的 UIImage 着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15999067/
我是一名优秀的程序员,十分优秀!