Swift 根据色码串获得UIColor

这篇博客介绍了如何使用Swift为UIColor类别添加一个方便的初始化方法,通过简单的字符串输入即可快速转换为RGB或RGBA颜色。它解决了将#RRGGBB或#RRGGBBAA形式的十六进制颜色字符串转换为UIColor对象的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import Foundation

import UIKit



extension UIColor {

    

    public convenience init(hex: String) {

        

        var red:   CGFloat = 0.0

        var green: CGFloat = 0.0

        var blue:  CGFloat = 0.0

        var alpha: CGFloat = 1.0

        var hex:   String = hex

        

        if hex.hasPrefix("#") {

            let index = hex.index(hex.startIndex, offsetBy: 1)

            hex = String(hex[index...])

        }

        

        let scanner = Scanner(string: hex)

        var hexValue: CUnsignedLongLong = 0

        if scanner.scanHexInt64(&hexValue) {

            switch (hex.count) {

            case 3:

                red   = CGFloat((hexValue & 0xF00) >> 8)       / 15.0

                green = CGFloat((hexValue & 0x0F0) >> 4)       / 15.0

                blue  = CGFloat(hexValue & 0x00F)              / 15.0

            case 4:

                red   = CGFloat((hexValue & 0xF000) >> 12)     / 15.0

                green = CGFloat((hexValue & 0x0F00) >> 8)      / 15.0

                blue  = CGFloat((hexValue & 0x00F0) >> 4)      / 15.0

                alpha = CGFloat(hexValue & 0x000F)             / 15.0

            case 6:

                red   = CGFloat((hexValue & 0xFF0000) >> 16)   / 255.0

                green = CGFloat((hexValue & 0x00FF00) >> 8)    / 255.0

                blue  = CGFloat(hexValue & 0x0000FF)           / 255.0

            case 8:

                red   = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0

                green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0

                blue  = CGFloat((hexValue & 0x0000FF00) >> 8)  / 255.0

                alpha = CGFloat(hexValue & 0x000000FF)         / 255.0

            default:

                debugPrint("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8", terminator: "")

            }

        } else {

            debugPrint("Scan hex error")

        }

        self.init(red:red, green:green, blue:blue, alpha:alpha)

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值