本文介绍了在ios中绘制图像的渐变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式创建渐变颜色,如下图所示。

How to create gradient colour look like following image programatically.

推荐答案

当你说将它作为渐变应用于图像时,你做到了吗?意思是作为一个面具(在顶部显示图像,让图像在底部淡化为透明)?如果是这种情况,您可以使用 CAGradientLayer :将该渐变应用为蒙版:

When you say "apply it over the image as a gradient", do you mean as a mask (revealing the image at the top, having it fade the image to transparent at the bottom)? If that's the case, you can apply that gradient as a mask, using CAGradientLayer:

CAGradientLayer *gradientMask = [CAGradientLayer layer];
gradientMask.frame = self.imageView.bounds;
gradientMask.colors = @[(id)[UIColor whiteColor].CGColor,
                        (id)[UIColor clearColor].CGColor];
self.imageView.layer.mask = gradientMask;






以上是一个简单的垂直渐变(因为默认是垂直,线性渐变)。但是你问过 startPoint endPoint locations 。例如,如果您希望水平应用蒙版,则可以执行以下操作:


The above does a simple vertical gradient (because the default is vertical, linear gradient). But you asked about startPoint, endPoint, and locations. If for example, you wanted your mask applied horizontally, you would do:

gradientMask.startPoint = CGPointMake(0.0, 0.5);   // start at left middle
gradientMask.endPoint = CGPointMake(1.0, 0.5);     // end at right middle

如果你想要两个渐变,一个在前10%和另一个在最后的10%,你会做:

If you wanted to have two gradients, one at the first 10% and another at the last 10%, you'd do:

gradientMask.colors = @[(id)[UIColor clearColor].CGColor,
                        (id)[UIColor whiteColor].CGColor,
                        (id)[UIColor whiteColor].CGColor,
                        (id)[UIColor clearColor].CGColor];
gradientMask.locations = @[@0.0, @0.10, @0.90, @1.0];






如果你想要一个简单的渐变(不是作为掩码),你创建一个视图,然后添加渐变图层:


If you want a simple gradient by itself (not as a mask), you'd create a view and then add the gradient layer to it:

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = @[(id)[UIColor whiteColor].CGColor,
                    (id)[UIColor blackColor].CGColor];
[view.layer addSublayer:gradient];

参见 CAGradientLayer

这篇关于在ios中绘制图像的渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 17:33