2016年6月8日 星期三

ColorPicker For Swift

since: 2016/06/08
update: 2016/06/08
reference:
1. johankasperi/SwiftHSVColorPicker
2. PrashantMangukiya/SwiftColorPicker
3. How to get the RGB Code (INT) from an UIColor in Swift - Stack Overflow


A. HSV Wheel Color Picker:
    1. 從
johankasperi/SwiftHSVColorPicker
        > 下載檔案: SwiftHSVColorPicker-master.zip
並解壓縮
        > 打開 SwiftHSVColorPickerExample.xcodeproj

    2. 修改: ViewController.swift 如下:
//
//  ViewController.swift
//  SwiftHSVColorPicker
//
//  Created by johankasperi on 2015-08-20.
//

//@add ####################
//
// Hue Saturation Value; HSV
//
// 係用一個倒六稜錐體定義顏色空間的模型。
// 其中,色調用H表示,以0到360度角表示各種顏色,如0度為紅色,120度為綠色。
// S為0與1間取值,反映顏色飽和或濃淡程度。
// V表示明度或亮度,在0與1間取值,0為最暗,1為最亮。


import Foundation
import UIKit
//@add ####################
import AudioToolbox

//@add ####################
extension UIColor {
    func rgb() -> (red:Int, green:Int, blue:Int, alpha:Int)? {
        var fRed : CGFloat = 0
        var fGreen : CGFloat = 0
        var fBlue : CGFloat = 0
        var fAlpha: CGFloat = 0
        if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
            let iRed = Int(fRed * 255.0)
            let iGreen = Int(fGreen * 255.0)
            let iBlue = Int(fBlue * 255.0)
            let iAlpha = Int(fAlpha * 255.0)
           
            return (red:iRed, green:iGreen, blue:iBlue, alpha:iAlpha)
        } else {
            // Could not extract RGBA components:
            return nil
        }
    }
}


//@add ####################
extension Int
{
    func toString() -> String
    {
        let myString = String(self)
        return myString
    }
}


//@add ####################
extension CGFloat
{
    func toString() -> String
    {
        let myString = String(self)
        return myString
    }
}


class ViewController: UIViewController {
   
    // Init ColorPicker with yellow
    var selectedColor: UIColor = UIColor.whiteColor()
   
    // IBOutlet for the ColorPicker
    @IBOutlet var colorPicker: SwiftHSVColorPicker!
   
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // Setup Color Picker
        colorPicker.setViewColor(selectedColor)
    }
   
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
    }
   
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
   
//    @IBAction func getSelectedColor(sender: UIButton) {
//        // Get the selected color from the Color Picker.
//        let selectedColor = colorPicker.color
//       
//        print(selectedColor)
//    }
   
    //@update  ####################
    @IBAction func getSelectedColor(sender: UIButton) {
        // Get the selected color from the Color Picker.
        // colorPicker.hue
        // colorPicker.saturation
        // colorPicker.brightness

        let selectedColor = colorPicker.color
        //print(selectedColor)
       
        AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate))
       
        if let rgb = selectedColor.rgb() {
            print()
            print(selectedColor)
            print("red = " + (rgb.red).toString())
            print("green = " + (rgb.green).toString())
            print("blue = " + (rgb.blue).toString())
            print("alpha = " + (rgb.alpha).toString())
            print("brightness = " + (colorPicker.brightness).toString())
        } else {
            print("conversion failed")
        }
    }

}

    3. 執行結果:



-----------------------------------------------------------------------------------------------

B. HSV Palette Color Picker:
    1. 從 PrashantMangukiya/SwiftColorPicker
        > 下載檔案: SwiftColorPicker-master.zip 並解壓縮
        > 打開 SwiftColorPicker \ SwiftColorPicker.xcodeproj

    2. 修改: ViewController.swift 如下:
//
//  ViewController.swift
//  SwiftColorPicker
//
//  Created by Prashant on 02/09/15.
//  Copyright (c) 2015 PrashantKumar Mangukiya. All rights reserved.
//
import UIKit

class ViewController: UIViewController, UIPopoverPresentationControllerDelegate, ColorPickerDelegate {
   
    // outlet - selected color preview
    @IBOutlet var colorPreview: UIView!
   
    // outlet - change color button
    @IBOutlet var changeColorButton: UIButton!
   
    // action - called when change color button clicked
    @IBAction func changeColorButtonClicked(sender: UIButton) {
        self.showColorPicker()
    }
   
    // outlet - change color button placed at navigation bar (right side)
    @IBOutlet var changeColorButtonNav: UIBarButtonItem!
   
    // action - change color button placed at navigation bar (right side)
    @IBAction func changeColorButtonNavClicked(sender: UIBarButtonItem) {
        self.showColorPickerFromNavBar()
    }
   
    // class varible maintain selected color value
    var selectedColor: UIColor = UIColor.blueColor()
    var selectedColorHex: String = "0000FF"
   
    // MARK: - View functions
   
    // called after view loaded
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // set corner radious
        self.colorPreview.layer.cornerRadius = self.colorPreview.layer.frame.width/6
       
        // set default background color
        self.colorPreview.backgroundColor = self.selectedColor
    }

    // called if received memory warning
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
   
    // MARK: Popover delegate functions

    // Override iPhone behavior that presents a popover as fullscreen.
    // i.e. now it shows same popover box within on iPhone & iPad
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
       
        // show popover box for iPhone and iPad both
        return UIModalPresentationStyle.None
    }
   
    // MARK: Color picker delegate functions
    // called by color picker after color selected.
    func colorPickerDidColorSelected(selectedUIColor selectedUIColor: UIColor, selectedHexColor: String) {
      
        // update color value within class variable
        self.selectedColor = selectedUIColor
        self.selectedColorHex = selectedHexColor
       
        // set preview background to selected color
        self.colorPreview.backgroundColor = selectedUIColor
       
        //@add ############################################
        print("selectedColorHex = "+selectedColorHex)
    }
  
    // MARK: - Utility functions
    // show color picker from UIButton
    private func showColorPicker(){
       
        // initialise color picker view controller
        let colorPickerVc = storyboard?.instantiateViewControllerWithIdentifier("sbColorPicker") as! ColorPickerViewController
       
        // set modal presentation style
        colorPickerVc.modalPresentationStyle = .Popover
       
        // set max. size
        colorPickerVc.preferredContentSize = CGSizeMake(265, 400)
       
        // set color picker deleagate to current view controller
        // must write delegate method to handle selected color
        colorPickerVc.colorPickerDelegate = self
       
        // show popover
        if let popoverController = colorPickerVc.popoverPresentationController {
           
            // set source view
            popoverController.sourceView = self.view
           
            // show popover form button
            popoverController.sourceRect = self.changeColorButton.frame
           
            // show popover arrow at feasible direction
            popoverController.permittedArrowDirections = UIPopoverArrowDirection.Any
           
            // set popover delegate self
            popoverController.delegate = self
        }
       
        //show color popover
        presentViewController(colorPickerVc, animated: true, completion: nil)
    }
   
   
    // show color picker from Navigation Bar Button
    private func showColorPickerFromNavBar(){
       
        // initialise color picker view controller
        let colorPickerVc = storyboard?.instantiateViewControllerWithIdentifier("sbColorPicker") as! ColorPickerViewController
       
        // set modal presentation style
        colorPickerVc.modalPresentationStyle = .Popover
       
        // set max. size
        colorPickerVc.preferredContentSize = CGSizeMake(265, 400)
       
        // set color picker deleagate to current view controller
        // must write delegate method to handle selected color
        colorPickerVc.colorPickerDelegate = self
       
        // show popover
        if let popoverController = colorPickerVc.popoverPresentationController {
           
            // show popover from navigation bar button
            popoverController.barButtonItem = self.changeColorButtonNav
           
            // show popover arrow at feasible direction
            popoverController.permittedArrowDirections = UIPopoverArrowDirection.Any
           
            // set popover delegate self
            popoverController.delegate = self
        }
       
        // show color popover
        presentViewController(colorPickerVc, animated: true, completion: nil)
    }
}

    3. 執行結果:


沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。