Supporting SwiftUI with Core Graphics

Nov 22 2022 Swift 5.5, iOS 15, Xcode 13

Part 1: Supporting SwiftUI with Core Graphics

8. Color Picking from a Bitmap Image

Episode complete

Save for later
About this episode
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 7. Create a Thumbnail

This video Color Picking from a Bitmap Image was last updated on Nov 22 2022

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

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.

DrawingColorView.swift

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.

DrawingPadExtensions.swift

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 = dataProvider.data
  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)

CanvasView.swift

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 {
  return
}
switch gesture.state {
case .began:
  drawingColorView.show(color: color, location: location)
case .ended:
  drawingColorView.hide()
  self.color = color
default: break
}
let longPress = UILongPressGestureRecognizer(target: self,
                                             action: #selector(handleLongPress))
addGestureRecognizer(longPress)
addSubview(drawingColorView)