简单的Swift颜色选择器弹出窗口(iOS)

44

有没有一种简单的方法在Swift中实现颜色选择弹出窗口?是否有任何内置库或UI元素可用于此目的?我看到了一些用Objective-C编写的颜色选择器,但它们已经过时了,我想知道是否有更近期的替代方案。

9个回答

97

这是我制作的一个非常简单的UIView。它允许您指定元素大小,以便在需要阻止区域(elementSize > 1)时使用。它会在接口构建器中绘制自己,因此您可以设置元素大小并查看其影响。只需在接口构建器中将其中一个视图设置为此类,然后将自己设置为委托即可。它会告诉您当有人点击或拖动它时该位置的UIColor。它会绘制到自己的边界中,除了这个类之外不需要任何其他东西,也不需要图片。

元素大小= 1(默认) 元素大小= 1

元素大小= 10
元素大小= 10

internal protocol HSBColorPickerDelegate : NSObjectProtocol {
    func HSBColorColorPickerTouched(sender:HSBColorPicker, color:UIColor, point:CGPoint, state:UIGestureRecognizerState)
}

@IBDesignable
class HSBColorPicker : UIView {

    weak internal var delegate: HSBColorPickerDelegate?
    let saturationExponentTop:Float = 2.0
    let saturationExponentBottom:Float = 1.3

    @IBInspectable var elementSize: CGFloat = 1.0 {
        didSet {
            setNeedsDisplay()
        }
    }

    private func initialize() {
        self.clipsToBounds = true
        let touchGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.touchedColor(gestureRecognizer:)))
        touchGesture.minimumPressDuration = 0
        touchGesture.allowableMovement = CGFloat.greatestFiniteMagnitude
        self.addGestureRecognizer(touchGesture)
    }

   override init(frame: CGRect) {
        super.init(frame: frame)
        initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initialize()
    }

    override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()
        for y : CGFloat in stride(from: 0.0 ,to: rect.height, by: elementSize) {
            var saturation = y < rect.height / 2.0 ? CGFloat(2 * y) / rect.height : 2.0 * CGFloat(rect.height - y) / rect.height
            saturation = CGFloat(powf(Float(saturation), y < rect.height / 2.0 ? saturationExponentTop : saturationExponentBottom))
            let brightness = y < rect.height / 2.0 ? CGFloat(1.0) : 2.0 * CGFloat(rect.height - y) / rect.height
            for x : CGFloat in stride(from: 0.0 ,to: rect.width, by: elementSize) {
                let hue = x / rect.width
                let color = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
                context!.setFillColor(color.cgColor)
                context!.fill(CGRect(x:x, y:y, width:elementSize,height:elementSize))
            }
        }
    }

    func getColorAtPoint(point:CGPoint) -> UIColor {
        let roundedPoint = CGPoint(x:elementSize * CGFloat(Int(point.x / elementSize)),
                               y:elementSize * CGFloat(Int(point.y / elementSize)))
        var saturation = roundedPoint.y < self.bounds.height / 2.0 ? CGFloat(2 * roundedPoint.y) / self.bounds.height
        : 2.0 * CGFloat(self.bounds.height - roundedPoint.y) / self.bounds.height
        saturation = CGFloat(powf(Float(saturation), roundedPoint.y < self.bounds.height / 2.0 ? saturationExponentTop : saturationExponentBottom))
        let brightness = roundedPoint.y < self.bounds.height / 2.0 ? CGFloat(1.0) : 2.0 * CGFloat(self.bounds.height - roundedPoint.y) / self.bounds.height
        let hue = roundedPoint.x / self.bounds.width
        return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
    }

    func getPointForColor(color:UIColor) -> CGPoint {
        var hue: CGFloat = 0.0
        var saturation: CGFloat = 0.0
        var brightness: CGFloat = 0.0
        color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: nil);

        var yPos:CGFloat = 0
        let halfHeight = (self.bounds.height / 2)
        if (brightness >= 0.99) {
            let percentageY = powf(Float(saturation), 1.0 / saturationExponentTop)
            yPos = CGFloat(percentageY) * halfHeight
        } else {
            //use brightness to get Y
            yPos = halfHeight + halfHeight * (1.0 - brightness)
        }
        let xPos = hue * self.bounds.width
        return CGPoint(x: xPos, y: yPos)
    }

    @objc func touchedColor(gestureRecognizer: UILongPressGestureRecognizer) {
        if (gestureRecognizer.state == UIGestureRecognizerState.began) {
            let point = gestureRecognizer.location(in: self)
            let color = getColorAtPoint(point: point)
            self.delegate?.HSBColorColorPickerTouched(sender: self, color: color, point: point, state:gestureRecognizer.state)
        }        
    }
}

25
我喜欢你将代码放在Stack Overflow这里,而不是链接到GitHub项目。 - Suragch
4
这里缺少的一件事是灰度。 - Suragch
看起来很漂亮,但我无法将其适应到我的现有Objective C项目中。实际上,我在包含上述代码的Swift文件中遇到了错误。我已经导入了UIKit,但对我来说它看起来像是Swift的语法发生了变化?上面的代码是否与Swift 2.3兼容?我使用的是Xcode 8.1。如果我表达不清楚,请见谅,因为我是新手。感谢您的建议。 - tsuyoski
当我回来时,我也会添加灰度。我们现在使用的是Swift 3.0,但如果有人想提供他们翻译的代码,我会更新它。 - Joel Teply
感谢您提供这段好的代码。我在从viewDidLoad中调用getPointForColor时遇到了一些问题:返回的点没有正确地定位到颜色视图中。事实证明,我们应该在所有自动布局调整操作完成后从viewDidLayoutSubviews中调用它。 - Laurent Maquet
显示剩余3条评论

30

我不知道这个答案中的答案在哪里。 - khunshan
你是如何生成这个特定的调色板的?它看起来是由程序和手动选择的颜色组合而成。整体效果比通常使用的RGB彩虹光谱要好得多。 - Womble
3
说实话,我在网上找到了一个颜色调色板,它只是由一位艺术家创建的图像。然后,我用吸管工具手动取样了所有图像颜色,并获得了它们的RGB值。您可以在此处找到所有值:https://github.com/EthanStrider/ColorPickerExample/blob/master/ColorPickerExample/colorPalette.plist - Ethan Strider
感谢 - 它完美地工作并且转换为Swift 5时没有太多问题。 - Jeremy Andrews

14

基于 Joel Teply 的代码(Swift 4),在顶部加上灰色条:

import UIKit


class ColorPickerView : UIView {

var onColorDidChange: ((_ color: UIColor) -> ())?

let saturationExponentTop:Float = 2.0
let saturationExponentBottom:Float = 1.3

let grayPaletteHeightFactor: CGFloat = 0.1
var rect_grayPalette = CGRect.zero
var rect_mainPalette = CGRect.zero

// adjustable
var elementSize: CGFloat = 1.0 {
    didSet {
        setNeedsDisplay()
    }
}

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

private func setup() {

    self.clipsToBounds = true
    let touchGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.touchedColor(gestureRecognizer:)))
    touchGesture.minimumPressDuration = 0
    touchGesture.allowableMovement = CGFloat.greatestFiniteMagnitude
    self.addGestureRecognizer(touchGesture)
}



override func draw(_ rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()

    rect_grayPalette = CGRect(x: 0, y: 0, width: rect.width, height: rect.height * grayPaletteHeightFactor)
    rect_mainPalette = CGRect(x: 0, y: rect_grayPalette.maxY,
                              width: rect.width, height: rect.height - rect_grayPalette.height)

    // gray palette
    for y in stride(from: CGFloat(0), to: rect_grayPalette.height, by: elementSize) {

        for x in stride(from: (0 as CGFloat), to: rect_grayPalette.width, by: elementSize) {
            let hue = x / rect_grayPalette.width

            let color = UIColor(white: hue, alpha: 1.0)

            context!.setFillColor(color.cgColor)
            context!.fill(CGRect(x:x, y:y, width:elementSize, height:elementSize))
        }
    }

    // main palette
    for y in stride(from: CGFloat(0), to: rect_mainPalette.height, by: elementSize) {

        var saturation = y < rect_mainPalette.height / 2.0 ? CGFloat(2 * y) / rect_mainPalette.height : 2.0 * CGFloat(rect_mainPalette.height - y) / rect_mainPalette.height
        saturation = CGFloat(powf(Float(saturation), y < rect_mainPalette.height / 2.0 ? saturationExponentTop : saturationExponentBottom))
        let brightness = y < rect_mainPalette.height / 2.0 ? CGFloat(1.0) : 2.0 * CGFloat(rect_mainPalette.height - y) / rect_mainPalette.height

        for x in stride(from: (0 as CGFloat), to: rect_mainPalette.width, by: elementSize) {
            let hue = x / rect_mainPalette.width

            let color = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)

            context!.setFillColor(color.cgColor)
            context!.fill(CGRect(x:x, y: y + rect_mainPalette.origin.y,
                                 width: elementSize, height: elementSize))
        }
    }
}



func getColorAtPoint(point: CGPoint) -> UIColor
{
    var roundedPoint = CGPoint(x:elementSize * CGFloat(Int(point.x / elementSize)),
                               y:elementSize * CGFloat(Int(point.y / elementSize)))

    let hue = roundedPoint.x / self.bounds.width


    // main palette
    if rect_mainPalette.contains(point)
    {
        // offset point, because rect_mainPalette.origin.y is not 0
        roundedPoint.y -= rect_mainPalette.origin.y

        var saturation = roundedPoint.y < rect_mainPalette.height / 2.0 ? CGFloat(2 * roundedPoint.y) / rect_mainPalette.height
            : 2.0 * CGFloat(rect_mainPalette.height - roundedPoint.y) / rect_mainPalette.height

        saturation = CGFloat(powf(Float(saturation), roundedPoint.y < rect_mainPalette.height / 2.0 ? saturationExponentTop : saturationExponentBottom))
        let brightness = roundedPoint.y < rect_mainPalette.height / 2.0 ? CGFloat(1.0) : 2.0 * CGFloat(rect_mainPalette.height - roundedPoint.y) / rect_mainPalette.height

        return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
    }
    // gray palette
    else{

        return UIColor(white: hue, alpha: 1.0)
    }
}


@objc func touchedColor(gestureRecognizer: UILongPressGestureRecognizer){
    let point = gestureRecognizer.location(in: self)
    let color = getColorAtPoint(point: point)

    self.onColorDidChange?(color)
  }
}

使用方法:

    let colorPickerView = ColorPickerView()
    colorPickerView.onColorDidChange = { [weak self] color in
        DispatchQueue.main.async {

            // use picked color for your needs here...
            self?.view.backgroundColor = color
        }

    }

    // add it to some view and set constraints
    ...

请问您能否解释一下如何在 VC 中使用这段代码?或者提供一个示例来说明如何使用它? - Fullpower
更新了我的答案。为了简单起见,去掉了委托。 - Michael Ros
MichaelRos,我按照以下方式尝试了你的代码,但当我点击按钮时没有任何反应。我做错了什么吗?class CustomizationViewController: UIViewController {@IBAction func backgroundColorSelector(_ sender: Any) { let colorPickerView = ColorPickerView() colorPickerView.onColorDidChange = { [weak self] color in DispatchQueue.main.async { self?.view.backgroundColor = color } } }} - Yan
通过添加一个UIView并将其分配给ColorPickerView类,我已经让它工作了。谢谢。 - Yan
1
@Yan 我也在视图控制器上添加了一个UIView,但是却没有看到任何东西。 - Raviteja Mathangi
你可以像这样将它包装在UIViewController中:class ColorPickerController: UIViewController { var setColor: ((UIColor) -> Void)? init() { super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { let colorPickerView = ColorPickerView() colorPickerView.onColorDidChange = setColor view = colorPickerView } }(将 ; 替换为新行) - aheze

13

这是 @joel-teply 关于 Swift 3.0 版本的回答:

internal protocol HSBColorPickerDelegate : NSObjectProtocol {
    func HSBColorColorPickerTouched(sender:HSBColorPicker, color:UIColor, point:CGPoint, state:UIGestureRecognizerState)
}

@IBDesignable
class HSBColorPicker : UIView {

    weak internal var delegate: HSBColorPickerDelegate?
    let saturationExponentTop:Float = 2.0
    let saturationExponentBottom:Float = 1.3

    @IBInspectable var elementSize: CGFloat = 1.0 {
        didSet {
            setNeedsDisplay()
        }
    }


    private func initialize() {

        self.clipsToBounds = true
        let touchGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.touchedColor(gestureRecognizer:)))
        touchGesture.minimumPressDuration = 0
        touchGesture.allowableMovement = CGFloat.greatestFiniteMagnitude
        self.addGestureRecognizer(touchGesture)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initialize()
    }

    override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()

        for y in stride(from: (0 as CGFloat), to: rect.height, by: elementSize) {

            var saturation = y < rect.height / 2.0 ? CGFloat(2 * y) / rect.height : 2.0 * CGFloat(rect.height - y) / rect.height
            saturation = CGFloat(powf(Float(saturation), y < rect.height / 2.0 ? saturationExponentTop : saturationExponentBottom))
            let brightness = y < rect.height / 2.0 ? CGFloat(1.0) : 2.0 * CGFloat(rect.height - y) / rect.height

            for x in stride(from: (0 as CGFloat), to: rect.width, by: elementSize) {
                let hue = x / rect.width
                let color = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
                context!.setFillColor(color.cgColor)
                context!.fill(CGRect(x:x, y:y, width:elementSize,height:elementSize))
            }
        }
    }

    func getColorAtPoint(point:CGPoint) -> UIColor {
        let roundedPoint = CGPoint(x:elementSize * CGFloat(Int(point.x / elementSize)),
                                   y:elementSize * CGFloat(Int(point.y / elementSize)))
        var saturation = roundedPoint.y < self.bounds.height / 2.0 ? CGFloat(2 * roundedPoint.y) / self.bounds.height
            : 2.0 * CGFloat(self.bounds.height - roundedPoint.y) / self.bounds.height
        saturation = CGFloat(powf(Float(saturation), roundedPoint.y < self.bounds.height / 2.0 ? saturationExponentTop : saturationExponentBottom))
        let brightness = roundedPoint.y < self.bounds.height / 2.0 ? CGFloat(1.0) : 2.0 * CGFloat(self.bounds.height - roundedPoint.y) / self.bounds.height
        let hue = roundedPoint.x / self.bounds.width
        return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
    }

    func getPointForColor(color:UIColor) -> CGPoint {
        var hue:CGFloat=0;
        var saturation:CGFloat=0;
        var brightness:CGFloat=0;
        color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: nil);

        var yPos:CGFloat = 0
        let halfHeight = (self.bounds.height / 2)

        if (brightness >= 0.99) {
            let percentageY = powf(Float(saturation), 1.0 / saturationExponentTop)
            yPos = CGFloat(percentageY) * halfHeight
        } else {
            //use brightness to get Y
            yPos = halfHeight + halfHeight * (1.0 - brightness)
        }

        let xPos = hue * self.bounds.width

        return CGPoint(x: xPos, y: yPos)
    }

    func touchedColor(gestureRecognizer: UILongPressGestureRecognizer){
        let point = gestureRecognizer.location(in: self)
        let color = getColorAtPoint(point: point)

        self.delegate?.HSBColorColorPickerTouched(sender: self, color: color, point: point, state:gestureRecognizer.state)
    }
}

9

iOS 14 现在已经实现了标准的UIColorPickerViewController和相关的UIColorWell。UIColorWell是一种颜色样本,它会自动弹出UIColorPicker供您选择颜色。

要测试ColorPicker,您可以使用Xcode 12或更高版本创建一个Swift App项目,目标iOS 14+,然后尝试以下简单代码:

import SwiftUI

struct ContentView: View {
    @State private var bgColor = Color.white

    var body: some View {
        VStack {
            ColorPicker("Set the background color",
                        selection: $bgColor,
                        supportsOpacity: true)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(bgColor)
    }
}

supportsOpacity更改为false,以摆脱不透明度滑块并仅允许完全不透明的颜色。

ColorPicker显示两种不同的选择模式:

iOS 14 ColorPicker

没有Alpha通道的ColorPicker:

iOS ColorPicker no alpha


我该如何在UIViewController类中使用常规Swift? - Ahmadreza

7

感谢提供的起点。

我在此基础上编写了一个完整的Color PickerViewController,包括自定义UIView和一些绘图代码。

我将自定义UIView设置为@IBDesignable,以便在InterfaceBuilder中呈现。

https://github.com/Christian1313/iOS_Swift_ColorPicker


2

我快速添加了代码,使用苹果在IOS 14中发布的颜色选择器为ViewController实现了一个颜色选择器。确保您的部署信息至少是IOS 14.0或更高版本。参见https://developer.apple.com/documentation/uikit/uicolorpickerviewcontroller以供参考。

将颜色选择器委托添加到类中,并声明一个颜色选择器对象:

class ViewController: UIViewController, UIColorPickerViewControllerDelegate  {
    
    let colorPicker = UIColorPickerViewController()

在viewDidLoad的最后,我将colorPicker的代理设置为self。
        colorPicker.delegate = self

    } // ends viewDidLoad

我使用一个单色选择器来为多个不同的对象选择颜色。当我向用户展示颜色选择器时,我设置布尔标志为true,以指示显示颜色选择器的原因。

        resetAllColorChangeFlags() // First make sure all the booleans are false for robust design

        changingScreenBackgroundColor = true

        present(colorPicker, animated: true, completion: nil)

我添加了处理 colorPickerViewControllerDidSelectColor 和 colorPickerViewControllerDidFinish 的 API。
colorPickerViewControllerDidSelectColor 检查布尔标志,并为适当的对象设置颜色属性。如果该颜色被应用于图层中的边框颜色,则使用 cgColor。
    func colorPickerViewControllerDidSelectColor(_ viewController: UIColorPickerViewController) {
        
        if changingScreenBackgroundColor
        {
            self.view.backgroundColor = viewController.selectedColor
        }
        if addingATintCircle
        {
            pointerToThisTintView.backgroundColor = viewController.selectedColor
        }
        if changingTextBackgroundColor
        {
            pointerToTextObjectSelected.backgroundColor = viewController.selectedColor
        }
        if changingTextColor
        {
            pointerToTextObjectSelected.textColor = viewController.selectedColor
        }
        if changingTextBorderColor
        {
            pointerToTextObjectSelected.layer.borderColor = viewController.selectedColor.cgColor
        }
        if changingPhotoBorderColor
        {
            pointerToPhotoObjectSelected.layer.borderColor = viewController.selectedColor.cgColor
        }
        if changingCameraBorderColor {
            cameraView.layer.borderColor = viewController.selectedColor.cgColor
        }
    } // ends colorPickerViewControllerDidSelectColor

colorPickerViewControllerDidFinish 用于重置所有布尔标志,这些标志指示为何将颜色选择器呈现给用户。


    func colorPickerViewControllerDidFinish(_ viewController: UIColorPickerViewController)
    {
        resetAllColorChangeFlags()

    } // ends colorPickerViewControllerDidFinish

这是我的重置例程:

    func resetAllColorChangeFlags()
    {
        changingFunTextColor = false
        changingFunTextFirstColorForGradient = false
        changingFunTextSecondColorForGradient = false
        changingScreenBackgroundColor = false
        changingTextBackgroundColor = false
        changingTextColor = false
        changingTextBorderColor = false
        changingPhotoBorderColor = false
        changingCameraBorderColor = false
        addingATintToAPhotoObject = false
        addingATintCircle = false
        addingAColorForGradients = false
        
    } // ends resetAllColorChangeFlags

1
最好创建一个枚举并使用switch。 - adougies

1

颜色选择器视图图片

在基于Christian1313的答案之上,我添加了更深的颜色

@IBDesignable final public class SwiftColorView: UIView {

weak var colorSelectedDelegate: ColorDelegate?

@IBInspectable public var numColorsX:Int =  10 {
    didSet {
        setNeedsDisplay()
    }
}

@IBInspectable public var numColorsY:Int = 18 {
    didSet {
        setNeedsDisplay()
    }
}

@IBInspectable public var coloredBorderWidth:Int = 10 {
    didSet {
        setNeedsDisplay()
    }
}

@IBInspectable public var showGridLines:Bool = false {
    didSet {
        setNeedsDisplay()
    }
}

weak var delegate: SwiftColorPickerDataSource?

public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let touch = touches.first else { return }
    let location = touch.location(in: self)

    colorSelectedDelegate?.setStroke(color: colorAtPoint(point: location))
}

public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let touch = touches.first else { return }
    let location = touch.location(in: self)

    colorSelectedDelegate?.setStroke(color: colorAtPoint(point: location))
}

public override func draw(_ rect: CGRect) {
    super.draw(rect)
    let lineColor = UIColor.gray
    let pS = patternSize()
    let w = pS.w
    let h = pS.h

    for y in 0..<numColorsY
    {
        for x in 0..<numColorsX
        {
            let path = UIBezierPath()
            let start = CGPoint(x: CGFloat(x)*w+CGFloat(coloredBorderWidth), y: CGFloat(y)*h+CGFloat(coloredBorderWidth))
            path.move(to: start);
            path.addLine(to: CGPoint(x: start.x+w, y: start.y))
            path.addLine(to: CGPoint(x: start.x+w, y: start.y+h))
            path.addLine(to: CGPoint(x: start.x, y: start.y+h))
            path.addLine(to: start)
            path.lineWidth = 0.25
            colorForRectAt(x: x,y:y).setFill();

            if (showGridLines)
            {
                lineColor.setStroke()
            }
            else
            {
                colorForRectAt(x: x, y: y).setStroke();
            }
            path.fill();
            path.stroke();
        }
    }
}

private func colorForRectAt(x: Int, y: Int) -> UIColor
{

    if let ds = delegate {
        return ds.colorForPalletIndex(x: x, y: y, numXStripes: numColorsX, numYStripes: numColorsY)
    } else {

        var hue:CGFloat = CGFloat(x) / CGFloat(numColorsX)
        var fillColor = UIColor.white
        if (y==0)
        {
            if (x==(numColorsX-1))
            {
                hue = 1.0;
            }
            fillColor = UIColor(white: hue, alpha: 1.0);
        }
        else
        {
            if y < numColorsY / 2 {
                //dark
                let length = numColorsY / 2
                let brightness: CGFloat = CGFloat(y) / CGFloat(length)
                fillColor = UIColor(hue: hue, saturation: 1.0, brightness: brightness, alpha: 1.0)
            } else if y == numColorsY / 2 {
                // normal
                fillColor = UIColor(hue: hue, saturation: 1.0, brightness: 1.0, alpha: 1.0)
            } else {
                // light
                let length = numColorsY / 2 - 1
                let offset = y - length - 1
                let sat:CGFloat = CGFloat(1.0) - CGFloat(offset) / CGFloat(length + 1)
                print("sat", sat)
                fillColor = UIColor(hue: hue, saturation: sat, brightness: 1.0, alpha: 1.0)
            }
        }
        return fillColor
    }
}

func colorAtPoint(point: CGPoint) -> UIColor
{
    let pS = patternSize()
    let w = pS.w
    let h = pS.h
    let x = (point.x-CGFloat(coloredBorderWidth))/w
    let y = (point.y-CGFloat(coloredBorderWidth))/h
    return colorForRectAt(x: Int(x), y:Int(y))
}

private func patternSize() -> (w: CGFloat, h:CGFloat)
{
    let width = self.bounds.width-CGFloat(2*coloredBorderWidth)
    let height = self.bounds.height-CGFloat(2*coloredBorderWidth)

    let w = width/CGFloat(numColorsX)
    let h = height/CGFloat(numColorsY)
    return (w,h)
}

public override func prepareForInterfaceBuilder()
{
    print("Compiled and run for IB")
}

}


0

使用Michael Ros的答案,

如果你想在Objective-C视图控制器中使用这个视图,你可以简单地创建一个名为ColorPickerView的新的Swift文件,并在Storyboard上向你的视图控制器添加一个UIView,并将其选择为ColorPickerView的类名。然后将你的视图控制器设置为名称为@"colorIsPicked"的通知观察者。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateColor) name:@"colorIsPicked" object:nil];

ColorPickerView.swift的代码

class ColorPickerView : UIView {

@objc public lazy var onColorDidChange: ((_ color: UIColor) -> ()) = {
           
    //send a notification for the caller view to update its elements if necessery
    NotificationCenter.default.post(name: Notification.Name("colorIsPicked"), object: nil)

}


let saturationExponentTop:Float = 2.0
let saturationExponentBottom:Float = 1.3

let grayPaletteHeightFactor: CGFloat = 0.1
var rect_grayPalette = CGRect.zero
var rect_mainPalette = CGRect.zero

// adjustable
var elementSize: CGFloat = 10.0 {
    didSet {
        setNeedsDisplay()
    }
}

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

private func setup() {
    
    self.clipsToBounds = true
    let touchGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.touchedColor(gestureRecognizer:)))
    touchGesture.minimumPressDuration = 0
    touchGesture.allowableMovement = CGFloat.greatestFiniteMagnitude
    self.addGestureRecognizer(touchGesture)
}



override func draw(_ rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()
    
    rect_grayPalette = CGRect(x: 0, y: 0, width: rect.width, height: rect.height * grayPaletteHeightFactor)
    rect_mainPalette = CGRect(x: 0, y: rect_grayPalette.maxY,
                              width: rect.width, height: rect.height - rect_grayPalette.height)
    
    // gray palette
    for y in stride(from: CGFloat(0), to: rect_grayPalette.height, by: elementSize) {
        
        for x in stride(from: (0 as CGFloat), to: rect_grayPalette.width, by: elementSize) {
            let hue = x / rect_grayPalette.width
            
            let color = UIColor(white: hue, alpha: 1.0)
            
            context!.setFillColor(color.cgColor)
            context!.fill(CGRect(x:x, y:y, width:elementSize, height:elementSize))
        }
    }
    
    // main palette
    for y in stride(from: CGFloat(0), to: rect_mainPalette.height, by: elementSize) {
        
        var saturation = y < rect_mainPalette.height / 2.0 ? CGFloat(2 * y) / rect_mainPalette.height : 2.0 * CGFloat(rect_mainPalette.height - y) / rect_mainPalette.height
        saturation = CGFloat(powf(Float(saturation), y < rect_mainPalette.height / 2.0 ? saturationExponentTop : saturationExponentBottom))
        let brightness = y < rect_mainPalette.height / 2.0 ? CGFloat(1.0) : 2.0 * CGFloat(rect_mainPalette.height - y) / rect_mainPalette.height
        
        for x in stride(from: (0 as CGFloat), to: rect_mainPalette.width, by: elementSize) {
            let hue = x / rect_mainPalette.width
            
            let color = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
            
            context!.setFillColor(color.cgColor)
            context!.fill(CGRect(x:x, y: y + rect_mainPalette.origin.y,
                                 width: elementSize, height: elementSize))
        }
    }
}



func getColorAtPoint(point: CGPoint) -> UIColor
{
    var roundedPoint = CGPoint(x:elementSize * CGFloat(Int(point.x / elementSize)),
                               y:elementSize * CGFloat(Int(point.y / elementSize)))
    
    let hue = roundedPoint.x / self.bounds.width
    
    
    // main palette
    if rect_mainPalette.contains(point)
    {
        // offset point, because rect_mainPalette.origin.y is not 0
        roundedPoint.y -= rect_mainPalette.origin.y
        
        var saturation = roundedPoint.y < rect_mainPalette.height / 2.0 ? CGFloat(2 * roundedPoint.y) / rect_mainPalette.height
            : 2.0 * CGFloat(rect_mainPalette.height - roundedPoint.y) / rect_mainPalette.height
        
        saturation = CGFloat(powf(Float(saturation), roundedPoint.y < rect_mainPalette.height / 2.0 ? saturationExponentTop : saturationExponentBottom))
        let brightness = roundedPoint.y < rect_mainPalette.height / 2.0 ? CGFloat(1.0) : 2.0 * CGFloat(rect_mainPalette.height - roundedPoint.y) / rect_mainPalette.height
        
        return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
    }
    // gray palette
    else{
        
        return UIColor(white: hue, alpha: 1.0)
    }
}


@objc func touchedColor(gestureRecognizer: UILongPressGestureRecognizer){
    let point = gestureRecognizer.location(in: self)
    let color = getColorAtPoint(point: point)
    
    self.onColorDidChange(color)
}
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接