Swift绘制渐变色的方法

本文实例为大家分享了Swift绘制渐变色的具体代码,供大家参考,具体内容如下

示意图:

import Foundation
import UIKit

class GradientVC: UIViewController {

    @IBOutlet weak var butOne: GradientCustomButton!
    @IBOutlet weak var viewTwo: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        /// 方式一 xib添加渐变色

        /// 方式一 代码添加渐变色
        butOne.isGradient = true
        butOne.startColor = UIColor(hexString: "#FD0134")!
        butOne.endColor = UIColor(hexString: "#007AFF")!
        butOne.startPoint = CGPoint(x: 0,y: 0)
        butOne.endPoint = CGPoint(x: 1,y: 1)

        /// 方式二
        //viewTwo.addGradient(start_color: "#8238FF", end_color: "#007AFF")
        //viewTwo.layer.masksToBounds = true
        viewTwo.addGradient(colors: [UIColor(hexString: "#FD0134")!, UIColor(hexString: "#007AFF")!],
                            point: (CGPoint(x: 1.0, y: 0.0), CGPoint(x: 0.0, y: 1.0)),
                            frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width-40, height: 100),
                            radius: 0)

    }
}

方式一:

使用xib或代码的方式添加渐变色.

这种方式有个缺点, 若是要对更多的视图(比如UILabel)添加渐变色, 需要继续创建一个子类继承于它进行功能的拓展.

import Foundation
import UIKit

class GradientCustomView: UIView {

    @IBInspectable var isGradient: Bool = false
    @IBInspectable var startColor: UIColor = .white
    @IBInspectable var endColor: UIColor = .white
    @IBInspectable var locations: [NSNumber] = [0 , 1]
    @IBInspectable var startPoint: CGPoint = .zero
    @IBInspectable var endPoint: CGPoint = .zero

    private var gradientBGLayer: CAGradientLayer?

    override func layoutSubviews() {
        super.layoutSubviews()
        gradientBGLayer?.removeFromSuperlayer()
        if isGradient {
            gradientBGLayer = CAGradientLayer()
            gradientBGLayer!.colors = [startColor.cgColor, endColor.cgColor]
            gradientBGLayer!.locations = locations
            gradientBGLayer!.frame = bounds
            gradientBGLayer!.startPoint = startPoint
            gradientBGLayer!.endPoint = endPoint
            self.layer.insertSublayer(gradientBGLayer!, at: 0)
        }
    }

}

class GradientCustomButton: UIButton {

    @IBInspectable var isGradient: Bool = false
    @IBInspectable var startColor: UIColor = .white
    @IBInspectable var endColor: UIColor = .white
    @IBInspectable var locations: [NSNumber] = [0 , 1]
    @IBInspectable var startPoint: CGPoint = .zero
    @IBInspectable var endPoint: CGPoint = .zero

    private var gradientBGLayer: CAGradientLayer?

    override func layoutSubviews() {
        super.layoutSubviews()
        gradientBGLayer?.removeFromSuperlayer()
        if isGradient {
            gradientBGLayer = CAGradientLayer()
            gradientBGLayer!.colors = [startColor.cgColor, endColor.cgColor]
            gradientBGLayer!.locations = locations
            gradientBGLayer!.frame = bounds
            gradientBGLayer!.startPoint = startPoint
            gradientBGLayer!.endPoint = endPoint
            self.layer.insertSublayer(gradientBGLayer!, at: 0)
        }
    }

}

方式二:

直接拓展UIView,让每个继承于UIView的视图都可以调用拓展的方法.

这种方式的缺点就是无法在Xib中使用

import Foundation
import UIKit

extension UIView {

    @discardableResult
    func addGradient(colors: [UIColor],
                     point: (CGPoint, CGPoint) = (CGPoint(x: 0.5, y: 0), CGPoint(x: 0.5, y: 1)),
                     locations: [NSNumber] = [0, 1],
                     frame: CGRect = CGRect.zero,
                     radius: CGFloat = 0,
                     at: UInt32 = 0) -> CAGradientLayer {
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = colors.map { $0.cgColor }
        bgLayer1.locations = locations
        if frame == .zero {
            bgLayer1.frame = self.bounds
        } else {
            bgLayer1.frame = frame
        }
        bgLayer1.startPoint = point.0
        bgLayer1.endPoint = point.1
        bgLayer1.cornerRadius = radius
        self.layer.insertSublayer(bgLayer1, at: at)
        return bgLayer1
    }

    func addGradient(start: CGPoint = CGPoint(x: 0.5, y: 0),
                     end: CGPoint = CGPoint(x: 0.5, y: 1),
                     colors: [UIColor],
                     locations: [NSNumber] = [0, 1],
                     frame: CGRect = CGRect.zero,
                     radius: CGFloat = 0,
                     at: UInt32 = 0) {
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = colors.map { $0.cgColor }
        bgLayer1.locations = locations
        bgLayer1.frame = frame
        bgLayer1.startPoint = start
        bgLayer1.endPoint = end
        bgLayer1.cornerRadius = radius
        self.layer.insertSublayer(bgLayer1, at: at)
    }

    func addGradient(start_color:String,end_color : String,frame : CGRect?=nil,cornerRadius : CGFloat?=0, at: UInt32 = 0){
        var bounds : CGRect = self.bounds
        if let frame = frame {
            bounds = frame
        }
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = [UIColor(hexString: start_color)!.cgColor, UIColor(hexString: end_color)!.cgColor]
        bgLayer1.locations = [0, 1]
        bgLayer1.frame = bounds
        bgLayer1.startPoint = CGPoint(x: 0, y: 0.61)
        bgLayer1.endPoint = CGPoint(x: 0.61, y: 0.61)
        bgLayer1.cornerRadius = cornerRadius ?? 0
        self.layer.insertSublayer(bgLayer1, at: at)
    }

    func addGradient(start_color:String,
                     end_color : String,
                     frame : CGRect?=nil,
                     borader: CGFloat = 0,
                     boraderColor: UIColor = .clear,
                     at: UInt32 = 0,
                     corners: UIRectCorner?,
                     radius: CGFloat = 0) {
        var bounds : CGRect = self.bounds
        if let frame = frame {
            bounds = frame
        }
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = [UIColor(hexString: start_color)!.cgColor, UIColor(hexString: end_color)!.cgColor]
        bgLayer1.locations = [0, 1]
        bgLayer1.frame = bounds
        bgLayer1.startPoint = CGPoint(x: 0, y: 0.61)
        bgLayer1.endPoint = CGPoint(x: 0.61, y: 0.61)
        bgLayer1.borderColor = boraderColor.cgColor
        bgLayer1.borderWidth = borader
        if corners != nil {
            let cornerPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners!, cornerRadii: CGSize(width: radius, height: radius))
            let radiusLayer = CAShapeLayer()
            radiusLayer.frame = bounds
            radiusLayer.path = cornerPath.cgPath
            bgLayer1.mask = radiusLayer
        }
        self.layer.insertSublayer(bgLayer1, at: at)
    }

    func addGradient(startPoint: CGPoint = CGPoint(x: 0, y: 0.5),
                     start_color:String,
                     endPoint: CGPoint = CGPoint(x: 1, y: 0.5),
                     end_color : String,
                     frame : CGRect? = nil,
                     cornerRadius : CGFloat?=0){
        var bounds : CGRect = self.bounds
        if let frame = frame {
            bounds = frame
        }
        let bgLayer1 = CAGradientLayer()
        bgLayer1.frame = bounds
        bgLayer1.startPoint = startPoint
        bgLayer1.endPoint = endPoint
        bgLayer1.colors = [UIColor(hexString: start_color)!.cgColor, UIColor(hexString: end_color)!.cgColor]
        bgLayer1.locations = [0, 1]
        bgLayer1.cornerRadius = cornerRadius ?? 0
        self.layer.addSublayer(bgLayer1)
    }

    func addVerticalGradient(start_color:String,end_color : String,frame : CGRect?=nil,cornerRadius : CGFloat?=0){
        var bounds : CGRect = self.bounds
        if let frame = frame {
            bounds = frame
        }
        let bgLayer1 = CAGradientLayer()
        bgLayer1.colors = [UIColor(hexString: start_color)!.cgColor, UIColor(hexString: end_color)!.cgColor]
        bgLayer1.locations = [0, 1]
        bgLayer1.frame = bounds
        bgLayer1.startPoint = CGPoint(x: 0.5, y: 0)
        bgLayer1.endPoint = CGPoint(x: 1, y: 1)
        bgLayer1.cornerRadius = cornerRadius ?? 0
        self.layer.insertSublayer(bgLayer1, at: 0)
    }

    //将当前视图转为UIImage
    func asImage() -> UIImage {
        let renderer = UIGraphicsImageRenderer(bounds: bounds)
        return renderer.image { rendererContext in
            layer.render(in: rendererContext.cgContext)
        }
    }
}

Demo:绘制渐变色

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • iOS SwiftUI 颜色渐变填充效果的实现

    SwiftUI 为我们提供了各种梯度选项,所有这些选项都可以通过多种方式使用. Gradient 渐变器 A color gradient represented as an array of color stops, each having a parametric location value. gradient是一组颜色的合集,每个颜色都忽略位置参数 LinearGradient 线性渐变器 线性渐变器拥有沿轴进行渐变函数,我们可以自定义设置颜色空间.起点和终点. 下面我们看看Linear

  • Swift绘制渐变色的方法

    本文实例为大家分享了Swift绘制渐变色的具体代码,供大家参考,具体内容如下 示意图: import Foundation import UIKit class GradientVC: UIViewController { @IBOutlet weak var butOne: GradientCustomButton! @IBOutlet weak var viewTwo: UIView! override func viewDidLoad() { super.viewDidLoad() ///

  • iOS中利用CAGradientLayer绘制渐变色的方法实例

    前言 以前不用自己切图,现在要自己切图,看到设计稿有好多不同规格的渐变色的背景,一个一个切的话好麻烦,没有想到iOS本来就可以实现渐变色.也就是今天的主角CAGradientLayer. 渐变色使用的类是CAGradientLayer,有两个要素,渐变颜色的起点和终点.渐变的颜色集合 简单示例: //设置渐变颜色 CAGradientLayer *gradientLayer = [CAGradientLayer layer]; gradientLayer.frame = view.bounds;

  • 基于Python+Matplotlib绘制渐变色扇形图与等高线图

    目录 渐变色扇形图 等高线 渐变色扇形图 使用 python - matplotlib 颜色地图plt.cm模块儿,来绘制出颜色渐变.更加好看的扇形图.也称彩虹图,但是也不限于彩虹图,可以选择的颜色地图(colormap)有: Paired, autumn, rainbow, gray, spring, Darks. 下边以颜色地图rainbow为例(彩虹图),写出以下代码,并展示各种颜色样式下的图像效果. import pandas as pd import numpy as np impor

  • python利用matplotlib库绘制饼图的方法示例

    介绍 matplotlib 是python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地进行制图.而且也可以方便地将它作为绘图控件,嵌入GUI应用程序中. 它的文档相当完备,并且 Gallery页面 中有上百幅缩略图,打开之后都有源程序.因此如果你需要绘制某种类型的图,只需要在这个页面中浏览/复制/粘贴一下,基本上都能搞定. matplotlib的安装方法可以点击这里 这篇文章给大家主要介绍了python用matplotlib绘制饼图的方法,话不多说,下面来看代码

  • asp.net实现C#绘制太极图的方法

    本文实例讲述了asp.net实现C#绘制太极图的方法.分享给大家供大家参考.具体如下: 成品图如下所示: html页面: 注意设置: 复制代码 代码如下: ContentType="Image/Jpeg" 复制代码 代码如下: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="TaiJiTu.aspx.cs" Inherits="TaiJiTu&qu

  • javascript+html5实现绘制圆环的方法

    本文实例讲述了javascript+html5实现绘制圆环的方法.分享给大家供大家参考.具体如下: <!DOCTYPE html> <html> <head> <title> </title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> </head> <body> <fiel

  • js+html5通过canvas指定开始和结束点绘制线条的方法

    本文实例讲述了js+html5通过canvas指定开始和结束点绘制线条的方法.分享给大家供大家参考.具体实现方法如下: <!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;"> Your browser does n

  • php绘制圆形的方法

    本文实例讲述了php绘制圆形的方法.分享给大家供大家参考.具体实现方法如下: php绘图的基本步骤,有四步(php.ini里的 extension = php_gb2.dll 组件首先需要启用) 1.创建画布: 2.画出所需要的图像(圆.直线.矩形.扇形.弧线.......): 3.输出到网页,或者另存: 4.销毁图片(目的是释放图像所占用的内存). 网站开发最常用的三种图像格式:gif.jpg/jpeg.png (1)gif格式:压缩率最高,但只能显示256色,可能造成色彩的丢失.优势:可能显

  • php使用Jpgraph绘制柱形图的方法

    本文实例讲述了php使用Jpgraph绘制柱形图的方法.分享给大家供大家参考.具体实现方法如下: <?php include ("src/jpgraph.php"); include ("src/jpgraph_bar.php"); $data = array(19,23,34,38,45,67,71,78,85,87,90,96); //定义数组 $graph = new Graph(400,300); //创建新的Graph对象 $graph->Se

  • Python使用matplotlib绘制动画的方法

    本文实例讲述了Python使用matplotlib绘制动画的方法.分享给大家供大家参考.具体分析如下: matplotlib从1.1.0版本以后就开始支持绘制动画 下面是几个的示例: 第一个例子使用generator,每隔两秒,就运行函数data_gen: # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation fig =

随机推荐