【问题标题】:Get UIImage with gradient fill color using core graphics使用核心图形获取具有渐变填充颜色的 UIImage
【发布时间】:2018-02-14 17:36:22
【问题描述】:

我正在为 UIImage 创建一个类别,在其中我传递一个图像并获取我提供的填充颜色的图像蒙版。现在我想添加渐变而不是单色填充。下面是我如何生成具有单一填充颜色的蒙版图像的方法。如何添加渐变而不是单色?

- (UIImage *)imageMaskedWithGradientColor:(UIColor *)maskColor
{
    NSParameterAssert(maskColor != nil);

        CGRect imageRect = CGRectMake(0.0f, 0.0f, self.size.width, self.size.height);
        UIImage *newImage = nil;

        UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, self.scale);
        {
            CGContextRef context = UIGraphicsGetCurrentContext();

            CGContextScaleCTM(context, 1.0f, -1.0f);
            CGContextTranslateCTM(context, 0.0f, -(imageRect.size.height));

            CGContextClipToMask(context, imageRect, self.CGImage);
            CGContextSetFillColorWithColor(context, maskColor.CGColor);
            CGContextFillRect(context, imageRect);

            newImage = UIGraphicsGetImageFromCurrentImageContext();
        }
        UIGraphicsEndImageContext();

        return newImage;
}

【问题讨论】:

    标签: ios objective-c uiimage core-graphics


    【解决方案1】:

    您可以通过以下代码添加渐变蒙版

    CAGradientLayer *gradientMask = [CAGradientLayer layer];
    gradientMask.frame = self.myImageView.bounds;
    gradientMask.colors = @[(id)[UIColor whiteColor].CGColor,
                            (id)[UIColor clearColor].CGColor];  // Change colors as you want
    self.myImageView.layer.mask = gradientMask;
    

    欲了解更多信息,请阅读 Apple 官方文档。为CAGradientLayer

    【讨论】:

    • 我正在以编程方式生成蒙版图像。你的解决方案行不通。
    • 意味着你的 imageView 是程序化的?
    • 我的意思是,我将以编程方式绘制图像。具有特定设计并在其中应用带有渐变的蒙版。
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    相关资源
    最近更新 更多