【问题标题】:UIImage Drawing with a color带有颜色的 UIImage 绘图
【发布时间】:2013-03-05 19:54:09
【问题描述】:

我有两个 UIImageView,我想将图像从一个复制到另一个并调整颜色,但这会导致奇怪的拉伸。

这是我用来制作副本的代码:

_selectedIcon.image = groupView.icon;
[ViewUtils colorImageView:_selectedIcon withRed:0.843 Green:0.3176 andBlue:0.066667];

如果我只使用第一行,它会很好地复制图像,看起来像这样:

它有点大,因为它看起来很突出。但它会复制并正确缩放。然后当我尝试给它上色时,它会这样做:

这是我用来为图像着色的代码:

+(void)colorImageView:(UIImageView*)source withRed:(CGFloat)red Green:(float)green andBlue:(float)blue
{
    // Create a context containing the image.
    UIGraphicsBeginImageContext(source.bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // The mask needs to be upside down for some reason
    CGContextTranslateCTM(context, 0, source.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextClipToMask(context, source.bounds, [source.image CGImage]);
    CGContextFillRect(context, source.bounds);

    [[UIColor colorWithRed:red green:green blue:blue alpha:1.0] set];
    UIBezierPath *imagePath = [UIBezierPath bezierPathWithRect:source.bounds];
    [imagePath fill];
    // Retrieve the new image.
    source.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
}

我尝试了许多不同的方法来缩放着色代码中的图像,但似乎没有任何效果。有人有建议吗?

【问题讨论】:

    标签: uiimage uigraphicscontext


    【解决方案1】:

    我想通了。图像正在拉伸以适合整个 UIImageView,因此我需要调整边界以使其正确缩放。这是我使用的代码:

    float ratioX = source.bounds.size.width / source.image.size.width;
    float ratioY = source.bounds.size.height / source.image.size.height;
    float ratio = MIN(ratioX, ratioY);
    CGRect bounds = CGRectMake(0, 0, source.image.size.width * ratio, source.image.size.height * ratio);
    

    【讨论】:

      猜你喜欢
      • 2018-09-24
      • 2015-07-27
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 2019-03-07
      • 2012-07-12
      • 2015-08-27
      • 2016-04-20
      相关资源
      最近更新 更多