swift 渐变
I am an iOS engineer, and last week I was converting a UI design into a screen on Xcode's interface builder, when I faced this layout:
我是一名iOS工程师,上周,当我遇到以下布局时,我将UI设计转换为Xcode的界面生成器上的屏幕:
So, the designer wanted a progress view containing a gradient fill, and this is how I built it on code:
因此,设计人员想要一个包含渐变填充的进度视图,这就是我在代码上构建它的方式:
First of all, I've created a UIImage
extension to initiate it with an array of UIColor
, which will be turned into a gradient. Also, I created a GradientOrientation
enum to specify if the gradient is vertical or horizontal. This way, we can use the UIImage
init in other UI components, such as UIImageView
.
首先,我创建了一个UIImage
扩展,以使用UIColor
数组启动它,它将被转换为渐变。 另外,我创建了一个GradientOrientation
枚举来指定渐变是垂直还是水平。 这样,我们可以在其他UI组件(例如UIImageView
使用UIImage
初始化。
Finally I've created the GradientProgressView
, a class extended from UIProgressView
which contains firstColor
and secondColor
. These variables were marked as IBInspectable
, so they can be assigned at the Interface Builder. By changing these colors either on storyboard or on code, the progress view's progressImage
will be set as a gradient starting at firstColor
and ending at secondColor
.
最后,我创建了GradientProgressView
,从扩展一个类UIProgressView
包含firstColor
和secondColor
。 这些变量被标记为IBInspectable
,因此可以在Interface Builder中对其进行分配。 通过改变这些颜色或者在故事板或代码,进度视图的progressImage
将被设置为一个梯度起始于firstColor
和在结束secondColor
。
That being done, we just need to change the GradientProgressView
's first and second colors and voilà, our progress views are now gradient-ready.
完成后,我们只需要更改GradientProgressView
的第一和第二种颜色和voilà ,我们的进度视图就可以进行渐变了。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/ef74889e9e3d9d19d4b87f377d6620eb.png)
swift 渐变