Supporting SwiftUI with Core Graphics

Nov 22 2022 · Swift 5.5, iOS 15, Xcode 13

Part 1: Supporting SwiftUI with Core Graphics

08. Color Picking from a Bitmap Image

Episode complete

About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 07. Create a Thumbnail

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

We’re going to do one more cool thing with our DrawingPad. Drawing programs often allow you to long press on a color and choose it as your drawing color.


The starter project for this video has a pre-built UIView class in DrawingColorView.swift. This will be the round view that magnifies the pixel color at the long press location.


Create a new Swift file called DrawingPadExtensions.swift. Import UIKit

import UIKit
extension UIImage {
  func getColor(at location: CGPoint) -> UIColor? {
guard let cgImage = cgImage,
let dataProvider = cgImage.dataProvider,
  let pixelData =
  else {
    return nil
let scale = UIScreen.main.scale
let pixelLocation = CGPoint(x: location.x * scale,
                            y: location.y * scale)
let pixel = cgImage.bytesPerRow * Int(pixelLocation.y) + 
            cgImage.bitsPerPixel / 8 * Int(pixelLocation.x)
guard pixel < CFDataGetLength(pixelData) else {
  print("WARNING: mismatch of pixel data")
  return nil
guard let pointer = CFDataGetBytePtr(pixelData) else {
  return nil
func convert(_ color: UInt8) -> CGFloat {
  CGFloat(color) / 255.0
let red = convert(pointer[pixel])
let green = convert(pointer[pixel + 1])
let blue = convert(pointer[pixel + 2])
let alpha = convert(pointer[pixel + 3])
return UIColor(red: red, green: green, blue: blue, alpha: alpha)


Open CanvasView.swift. Create a new property to hold a DrawingColorView.

private let drawingColorView = DrawingColorView()
@objc func handleLongPress(gesture: UILongPressGestureRecognizer) {
  guard let drawingImage = drawingImage else { return }
let location = gesture.location(in: self)
guard let color = drawingImage.getColor(at: location) else {
switch gesture.state {
case .began: color, location: location)
case .ended:
  self.color = color
default: break
let longPress = UILongPressGestureRecognizer(target: self,
                                             action: #selector(handleLongPress))