//
// UiColorExtension.swift
// geekTime
//
// Created by liuan on 2020/9/14.
// Copyright © 2020 liuan. All rights reserved.
//
import UIKit
extension UIColor {
static func hexColor(_ hexValue:Int,alpahValue:Float)->UIColor{
return UIColor(red: CGFloat((hexValue & 0xFF0000) >> 16 ) / 255, green: CGFloat((hexValue & 0x00FF00) >> 8) / 255, blue: CGFloat(hexValue & 0x0000FF ) / 255, alpha: CGFloat(alpahValue))
}
static func hexColor(_ hexValue:Int)->UIColor{
return hexColor(hexValue,alpahValue: 1)
}
convenience init(_ hexValue:Int,alpahValue:Float) {
self.init(red: CGFloat((hexValue & 0xFF0000) >> 16 ) / 255, green: CGFloat((hexValue & 0x00FF00) >> 8) / 255, blue: CGFloat(hexValue & 0x0000FF ) / 255, alpha: CGFloat(alpahValue))
}
convenience init(_ hexValue:Int) {
self.init(hexValue,alpahValue:1)
}
convenience init(r:CGFloat,g:CGFloat,b:CGFloat,alpha:CGFloat = 1.0){
self.init(displayP3Red: r/255.0, green: g/255.0, blue: b/255.0, alpha: alpha)
}
class func globalBackGroundColor() -> UIColor{
return UIColor(r: 248, g: 249, b: 247)
}
}
怎么使用?
loginButton.backgroundColor = UIColor.hexColor(0xf8892e)
效果有是有了,但是你点击按钮的时候却没有反馈的那种变暗的效果。。
是因为button 这样设置上去背景是优点问题的
可以通过另外一个扩展 toImage
//
// UiColorExtension.swift
// geekTime
//
// Created by liuan on 2020/9/14.
// Copyright © 2020 liuan. All rights reserved.
//
import Foundation
import UIKit
extension UIColor{
static func hexColor(_ hexValue:Int,alpahValue:Float)->UIColor{
return UIColor(red: CGFloat((hexValue & 0xFF0000) >> 16 ) / 255, green: CGFloat((hexValue & 0x00FF00) >> 8) / 255, blue: CGFloat(hexValue & 0x0000FF ) / 255, alpha: CGFloat(alpahValue))
}
static func hexColor(_ hexValue:Int)->UIColor{
return hexColor(hexValue,alpahValue: 1)
}
convenience init(_ hexValue:Int,alpahValue:Float) {
self.init(red: CGFloat((hexValue & 0xFF0000) >> 16 ) / 255, green: CGFloat((hexValue & 0x00FF00) >> 8) / 255, blue: CGFloat(hexValue & 0x0000FF ) / 255, alpha: CGFloat(alpahValue))
}
convenience init(_ hexValue:Int) {
self.init(hexValue,alpahValue:1)
}
//颜色转换图片
func toImage()-> UIImage{
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(self.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
用法
// loginButton.backgroundColor = UIColor.hexColor(0xf8892e)
loginButton.setBackgroundImage(UIColor.hexColor(0xf8892e).toImage(), for: .normal)
点击的时候可以看到变暗。这便是这个扩展的作用。