如何使用渐变颜色填充贝塞尔曲线路径 [英] How to fill a bezier path with gradient color

查看:881
本文介绍了如何使用渐变颜色填充贝塞尔曲线路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的自定义 UIView绘图(_ rect:CGRect)函数中有 UIBezierPath 。我想用渐变色填充路径。请任何人都可以指导我怎么做。

I have a UIBezierPath inside my custom UIView draw(_ rect: CGRect) function. I would like to fill the path with a gradient color. Please can anybody guide me how can I do that.

我需要用渐变颜色填充剪辑,然后用黑色描边路径。

I need to fill the clip with a gradient color and then stroke the path with black color.

SO中有一些帖子无法解决问题。例如, Swift:沿着bezier路径的渐变(使用CALayers)这篇文章指导如何在 UIView 中绘制图层,但不在 UIBezierPath 中绘制。

There are some posts in SO which does not solve the problem. For example Swift: Gradient along a bezier path (using CALayers) this post guides how to draw on a layer in UIView but not in a UIBezierPath.

注意:我正在研究Swift-3

推荐答案

要回答你的这个问题,


我的自定义UIView绘图(_ rect:CGRect)
函数中有一个UIBezierPath。我想用渐变色填充路径。

I have a UIBezierPath inside my custom UIView draw(_ rect: CGRect) function. I would like to fill the path with a gradient color.

假设你有一个椭圆形路径,

Lets say you have an oval path,

let path = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))

要创建渐变,

let gradient = CAGradientLayer()
gradient.frame = path.bounds
gradient.colors = [UIColor.magenta.cgColor, UIColor.cyan.cgColor]

我们需要一个渐变的遮罩层,

We need a mask layer for gradient,

let shapeMask = CAShapeLayer()
shapeMask.path = path.cgPath

现在设置此 shapeLayer as 掩码 渐​​变图层并将其添加到查看的图层为 subLayer

Now set this shapeLayer as mask of gradient layer and add it to view's layer as subLayer

gradient.mask = shapeMask
yourCustomView.layer.addSublayer(gradient)

更新
创建包含笔划和广告的基础图层d在创建渐变图层之前。

Update Create a base layer with stroke and add before creating gradient layer.

let shape = CAShapeLayer()
shape.path = path.cgPath
shape.lineWidth = 2.0
shape.strokeColor = UIColor.black.cgColor
self.view.layer.addSublayer(shape)

let gradient = CAGradientLayer()
gradient.frame = path.bounds
gradient.colors = [UIColor.magenta.cgColor, UIColor.cyan.cgColor]

let shapeMask = CAShapeLayer()
shapeMask.path = path.cgPath
gradient.mask = shapeMask

self.view.layer.addSublayer(gradient)

这篇关于如何使用渐变颜色填充贝塞尔曲线路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆