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

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

问题描述

我的自定义 UIView draw(_ 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:沿贝塞尔路径渐变(使用 CALayer) 这篇文章将指导如何在 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 draw(_ 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设置为gradient图层的mask,并将其添加到view的图层中为<代码>子层

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)

更新使用描边创建基础图层并在创建渐变图层之前添加.

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天全站免登陆