Skip to content

Instantly share code, notes, and snippets.

@chunkyguy
Created December 23, 2020 16:02
Show Gist options
  • Save chunkyguy/d9e4118179fec01a356640d138de8ba0 to your computer and use it in GitHub Desktop.
Save chunkyguy/d9e4118179fec01a356640d138de8ba0 to your computer and use it in GitHub Desktop.
Use UIColorPickerViewController to pick color from the selected image
class ViewController: UIViewController {
private let imagePicker = UIImagePickerController()
private let colorPicker = UIColorPickerViewController()
private let imageView = UIImageView(image: nil)
private let colorView = UIView()
private let isSetUp = false
override func viewDidLayoutSubviews() {
if !isSetUp {
setUp()
}
}
private func setUp() {
let insets = view.safeAreaInsets
let toolBar = UIToolbar()
toolBar.frame = CGRect(x: 0, y: insets.top, width: view.bounds.width, height: 44)
toolBar.items = [
UIBarButtonItem(title: "Photo", style: .plain, target: self, action: #selector(openImagePicker)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "Color Picker", style: .plain, target: self, action: #selector(openColorPicker)),
]
view.addSubview(toolBar)
imagePicker.delegate = self
imagePicker.mediaTypes = ["public.image"]
imagePicker.sourceType = .photoLibrary
colorPicker.supportsAlpha = true
colorPicker.selectedColor = UIColor.blue
colorPicker.delegate = self
let contentFrame = CGRect(x: 0, y: toolBar.frame.maxY, width: view.bounds.width, height: view.bounds.height - insets.bottom)
let (slice, remainder) = contentFrame.divided(atDistance: view.bounds.width, from: .minYEdge)
imageView.frame = slice
imageView.contentMode = .scaleAspectFill
view.addSubview(imageView)
colorView.frame = remainder
view.addSubview(colorView)
colorView.backgroundColor = .black
imageView.backgroundColor = .darkGray
view.backgroundColor = .white
}
@objc func openImagePicker() {
present(imagePicker, animated: true)
}
@objc func openColorPicker() {
present(colorPicker, animated: true, completion: nil)
}
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
imageView.image = info[.originalImage] as? UIImage
picker.dismiss(animated: true, completion: nil)
}
}
extension ViewController: UIColorPickerViewControllerDelegate {
func colorPickerViewControllerDidSelectColor(_ viewController: UIColorPickerViewController) {
colorView.backgroundColor = viewController.selectedColor
}
func colorPickerViewControllerDidFinish(_ viewController: UIColorPickerViewController) {
viewController.dismiss(animated: true, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment