如何向 UIView 添加径向渐变?
我有一个 UIView,我想要一个径向渐变,我想知道如何做到这一点?
I have a UIView
which I want to have a radial gradient, and I'm wondering how to go about doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Swift 3 - @IBDesignable
我研究了 Karlis 和 Alexander 的答案。我的目标是尽可能地简化。例如删除颜色空间和位置 (
nil
),以便渐变使用默认值。如何使用
第1步
创建文件并添加以下代码:
import UIKit
步骤 2
在 Storyboard 上,将 UIView 设置为上面 Identity Inspector 中的
RadialGradientView
:步骤 3
在属性检查器中设置渐变的内部颜色和外部颜色,并在故事板上查看更改:
(注意:我将 Storyboard 上的 UIView 做得足够大,以便它填满整个
Swift 3 - @IBDesignable
I worked off Karlis and Alexander's answers. I aimed to simplify as much as possible. Such as removing color space and locations (
nil
) so the gradient uses the defaults.How to Use
Step 1
Create file and add this code:
import UIKit
Step 2
On Storyboard, set the UIView to the above
RadialGradientView
in Identity Inspector:Step 3
Set the Inside Color and Outside Color for your gradient in Attributes Inspector and see the change on your Storyboard:
(Note: I made the UIView on the Storyboard big enough to so it fills the entire
首先子类化 UIView:
然后将其添加到您的视图中:
结果:
First subclass a UIView:
And then add it to your view:
Result:
为此,您需要下拉至 Core Graphics 并使用 CGContextDrawRadialGradient。
类似的 Stack Overflow 问题
如何我可以画一个径向渐变的扇形吗(iphone)
如何绘制渐变线(淡入淡出输入/输出)与 Core Graphics/iPhone?
其他资源
这里有一个教程,展示如何在 iOS 上绘制带有渐变的图标:
http://redartisan.com/2011/05/13/porting-iconapp- core-graphics
他将代码放到了 Github 上,其中包含一个 UIView 子类,该子类展示了使用 Core Graphics 制作渐变的(相当冗长的)方法:
https://github.com/crafterm/IconApp/blob/master/ IconApp/IconView.m
To do this you need to drop down to Core Graphics and use CGContextDrawRadialGradient.
Similar Stack Overflow Questions
How can I draw a sector with radial gradient (iphone)
How to draw a gradient line (fading in/out) with Core Graphics/iPhone?
Other Resources
There's a tutorial showing how to draw icons with gradients on iOS here:
http://redartisan.com/2011/05/13/porting-iconapp-core-graphics
He's put the code on Github, complete with a UIView subclass that shows the (rather longwinded) way of making gradients using Core Graphics:
https://github.com/crafterm/IconApp/blob/master/IconApp/IconView.m
这是 Karlis 在 Swift 3 中的回答:
Here's Karlis' answer in Swift 3:
这是 Karlis 在 C# 中针对 Xamarin.iOS 的回答。这里我直接指定颜色,但你当然可以像 Karlis 那样实现它。
Here's Karlis answer in c# for Xamarin.iOS. Here I am specifying the colors directly but you can of course implement it the same way Karlis did.