将UIImage着色为不同的颜色,或者,从矢量生成UIImage



我有一个黑色轮廓的圆圈和一个白色填充,我需要通过编程将白色变成另一种颜色(通过UIColor)。我尝试过其他一些stackoverflow解决方案,但似乎没有一个能正确工作,要么只是填充外部,要么只是一个轮廓。

我有两种方法可以做到这一点,但我不确定如何才能得到正确的结果:

将白色着色为UIColor应该是的颜色,

或者,

从两个圆圈中制作一个UIImage,一个圆圈被填充,另一个圆圈用黑色重叠。

如果您决定使用两个圆圈,一个白色,一个黑色,那么您可能会发现这很有帮助。此方法将为您着色uiimage,但它解决了仅着色不透明部分的问题,这意味着如果您在圆周围提供透明的png,它将仅着色圆。因此,它没有填充图像的整个24x24帧,而是只填充不透明部分。这并不完全是你的问题,但如果你选择你列出的第二个选项,你可能会遇到这个问题。

-(UIImage*)colorAnImage:(UIColor*)color :(UIImage*)image{
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, image.scale);
CGContextRef c = UIGraphicsGetCurrentContext();
[image drawInRect:rect];
CGContextSetFillColorWithColor(c, [color CGColor]);
CGContextSetBlendMode(c, kCGBlendModeSourceAtop);
CGContextFillRect(c, rect);
UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return result;

}

扩展UIView并只实现drawRect方法。例如,这将绘制一个带有黑色轮廓的绿色圆圈。

     - (void)drawRect:(CGRect)rect {
          [super drawRect:rect];
          CGContextRef gc = UIGraphicsGetCurrentContext();
          [[UIColor greenColor] setFill];
          CGContextFillEllipseInRect(gc, CGRectMake(0,0,24,24));
          [[UIColor blackColor] set];
          CGContextStrokeEllipseInRect(gc, CGRectMake(0,0,24,24));
    }

对于这种简单的形状,只需使用CoreGraphics绘制一个正方形和一个圆形,就可以在实现中设置填充颜色。

如果只是黑色和白色,那么当你知道颜色表示时,将白色更改为另一种颜色就不那么困难了。不幸的是,这编写和执行起来更复杂,所以……我的建议是直接去CoreGraphics完成你概述的简单任务(糟糕的双关语,对不起)。

这里有一个快速演示:

static void InsetRect(CGRect* const pRect, const CGFloat pAmount) {
    const CGFloat halfAmount = pAmount * 0.5f;
    *pRect = CGRectMake(pRect->origin.x + halfAmount, pRect->origin.y + halfAmount, pRect->size.width - pAmount, pRect->size.height - pAmount);
}
static void DrawBorderedCircleWithWidthInContext(const CGRect pRect, const CGFloat pWidth, CGContextRef pContext) {
    CGContextSetLineWidth(pContext, pWidth);
    CGContextSetShouldAntialias(pContext, true);
    CGRect r = pRect;
    /* draw circle's border */
    CGContextSetRGBStrokeColor(pContext, 0.8f, 0.7f, 0, 1);
    InsetRect(&r, pWidth);
    CGContextStrokeEllipseInRect(pContext, r);
    /* draw circle's fill */
    CGContextSetRGBFillColor(pContext, 0, 0, 0.3f, 1);
    InsetRect(&r, pWidth);
    CGContextFillEllipseInRect(pContext, r);
}

相关内容

最新更新