Skip to main content
MyWebForum

Back to all posts

How to Detect If Color Is White Or Black In Swift?

Published on
10 min read
How to Detect If Color Is White Or Black In Swift? image

Best Color Detection Tools to Buy in February 2026

1 Nix Mini 3 Color Sensor Colorimeter - Portable Color Matching Tool - Dust Debris and Splash Resistant (IPX4) - Identify and match paint and digital color values instantly

Nix Mini 3 Color Sensor Colorimeter - Portable Color Matching Tool - Dust Debris and Splash Resistant (IPX4) - Identify and match paint and digital color values instantly

  • INSTANTLY MATCH 300,000+ BRAND NAME PAINTS WITH A SIMPLE SCAN!

  • GAIN DIGITAL COLOR VALUES: RGB, HEX, CMYK AND MORE IN SECONDS!

  • DUST AND WATER-RESISTANT DESIGN ENSURES DURABILITY FOR YEARS!

BUY & SAVE
Nix Mini 3 Color Sensor Colorimeter - Portable Color Matching Tool - Dust Debris and Splash Resistant (IPX4) - Identify and match paint and digital color values instantly
2 COLOR MUSE 3 Portable Color Matching and Paint Scanner Device – Wireless Digital Colorimeter Sensor for Accurate Color and Sheen Detection – Pocket-Sized, Easy Carry, Indoor/Outdoor Projects – Black

COLOR MUSE 3 Portable Color Matching and Paint Scanner Device – Wireless Digital Colorimeter Sensor for Accurate Color and Sheen Detection – Pocket-Sized, Easy Carry, Indoor/Outdoor Projects – Black

  • 精准的颜色和光泽匹配,一次扫描搞定!
  • 12X超长待机,便携式设计,随时随地快速使用!
  • 包含RAL和潘通库,轻松访问10万+产品颜色!
BUY & SAVE
Save 24%
COLOR MUSE 3 Portable Color Matching and Paint Scanner Device – Wireless Digital Colorimeter Sensor for Accurate Color and Sheen Detection – Pocket-Sized, Easy Carry, Indoor/Outdoor Projects – Black
3 Treedix USB Cable Tester with 2.4" Color Screen for eMarker Reading, PD 3.0/3.1 Detection, Resistor and Continuity Check, Compatible with Lightning, Type-C, Micro-B 2.0/3.0, and Mini-B Cables

Treedix USB Cable Tester with 2.4" Color Screen for eMarker Reading, PD 3.0/3.1 Detection, Resistor and Continuity Check, Compatible with Lightning, Type-C, Micro-B 2.0/3.0, and Mini-B Cables

  • TEST USB CABLES FOR FUNCTIONALITY, SAFETY, AND PERFORMANCE EFFICIENCY.
  • READ TYPE-C EMARKER CHIP FOR DETAILED CABLE PERFORMANCE INSIGHTS.
  • HIGH-DEFINITION DISPLAY FOR REAL-TIME CABLE STATUS AND QUALITY CHECKS.
BUY & SAVE
Save 9%
Treedix USB Cable Tester with 2.4" Color Screen for eMarker Reading, PD 3.0/3.1 Detection, Resistor and Continuity Check, Compatible with Lightning, Type-C, Micro-B 2.0/3.0, and Mini-B Cables
4 Pinless Moisture Meter for Wall,Floor – Digital Moisture Tester with 3-Color LCD Display, Audible Alarm & HOLD Function – Ideal for Home Inspections (Red_green)

Pinless Moisture Meter for Wall,Floor – Digital Moisture Tester with 3-Color LCD Display, Audible Alarm & HOLD Function – Ideal for Home Inspections (Red_green)

  • FAST & CONSISTENT READINGS: GET INSTANT MOISTURE RESULTS ON VARIOUS SURFACES.

  • PREVENT WATER DAMAGE: DETECT LEAKS AND HUMIDITY EARLY FOR TIMELY ACTION.

  • PINLESS TECHNOLOGY: MEASURE MOISTURE SAFELY WITHOUT DAMAGING SURFACES.

BUY & SAVE
Pinless Moisture Meter for Wall,Floor – Digital Moisture Tester with 3-Color LCD Display, Audible Alarm & HOLD Function – Ideal for Home Inspections (Red_green)
5 ptiysta Brake Disc Measuring Tool, 8-Piece SAE Gauge Measuring Metric Steel Structure Thickness Gauge, Color Coded Gauge Size, Measuring Disc and Drum Brake Pad Gauge

ptiysta Brake Disc Measuring Tool, 8-Piece SAE Gauge Measuring Metric Steel Structure Thickness Gauge, Color Coded Gauge Size, Measuring Disc and Drum Brake Pad Gauge

  • FAST & ACCURATE BRAKE THICKNESS DETECTION FOR SAFETY.

  • COMPATIBLE WITH METRIC AND SAE: VERSATILE FOR ALL VEHICLES.

  • DURABLE STEEL CONSTRUCTION WITH LIFETIME WARRANTY ASSURANCE.

BUY & SAVE
ptiysta Brake Disc Measuring Tool, 8-Piece SAE Gauge Measuring Metric Steel Structure Thickness Gauge, Color Coded Gauge Size, Measuring Disc and Drum Brake Pad Gauge
6 Bawkars 8 PCS Tire Pressure Monitor Valve Stem Caps, 2.4Bar 36PSI 3-Color Eye Alert Sensor Indicator, Tire Pressure Detection Warning Cap, Universal for Most Cars (Silver)​

Bawkars 8 PCS Tire Pressure Monitor Valve Stem Caps, 2.4Bar 36PSI 3-Color Eye Alert Sensor Indicator, Tire Pressure Detection Warning Cap, Universal for Most Cars (Silver)​

  • INSTANT PRESSURE ALERTS: 3-COLOR SYSTEM FOR QUICK TIRE PRESSURE CHECKS.
  • NO HASSLE INSTALLATION: TOOL-FREE SETUP FOR EFFORTLESS DAILY USE.
  • DURABLE DESIGN: BUILT TO WITHSTAND TOUGH WEATHER AND ROAD CONDITIONS.
BUY & SAVE
Save 11%
Bawkars 8 PCS Tire Pressure Monitor Valve Stem Caps, 2.4Bar 36PSI 3-Color Eye Alert Sensor Indicator, Tire Pressure Detection Warning Cap, Universal for Most Cars (Silver)​
7 K Tool International XDCHT504 Xtra Duty Cordless Circuit Tester, DC Voltage Detection Tool, Dual Color LED Polarity Indicator, Audible Beep Alert, Built in Lithium Battery

K Tool International XDCHT504 Xtra Duty Cordless Circuit Tester, DC Voltage Detection Tool, Dual Color LED Polarity Indicator, Audible Beep Alert, Built in Lithium Battery

  • QUICK DC VOLTAGE DETECTION FOR CARS, TRUCKS, AND MOTORCYCLES.
  • DUAL COLOR LEDS OFFER CLEAR VISUAL FEEDBACK DURING TESTING.
  • CORDLESS, COMPACT DESIGN ENSURES PORTABILITY AND EXTENDED USE.
BUY & SAVE
K Tool International XDCHT504 Xtra Duty Cordless Circuit Tester, DC Voltage Detection Tool, Dual Color LED Polarity Indicator, Audible Beep Alert, Built in Lithium Battery
8 Water-Spotter Leak Detection Sticker (Pack of 12), Easily Locate Intermittent and Hard-to-Find Leaks Anywhere, Permanently Turns Blue with Water Contact

Water-Spotter Leak Detection Sticker (Pack of 12), Easily Locate Intermittent and Hard-to-Find Leaks Anywhere, Permanently Turns Blue with Water Contact

  • INSTANT LEAK DETECTION: COLOR CHANGE ALERTS EVEN TINY LEAKS!

  • VERSATILE USES: PERFECT FOR HOMES, BOATS, AND APPLIANCES.

  • EASY APPLICATION: PLACE STICKERS AND LET THEM DO THE WORK!

BUY & SAVE
Water-Spotter Leak Detection Sticker (Pack of 12), Easily Locate Intermittent and Hard-to-Find Leaks Anywhere, Permanently Turns Blue with Water Contact
9 PETiB Vibration Noise Electronic Sensor Paranormal Investigation Tool Spirit Box Equipment Ghost Hunting Device EVP Sound Pickup Atmosphere Light with RGB Colors 8

PETiB Vibration Noise Electronic Sensor Paranormal Investigation Tool Spirit Box Equipment Ghost Hunting Device EVP Sound Pickup Atmosphere Light with RGB Colors 8

  • COMPACT DESIGN FOR EASY HANDLING DURING PARANORMAL INVESTIGATIONS.
  • HIGH SENSITIVITY MIC CAPTURES SUBTLE SOUNDS FOR SERIOUS RESEARCH.
  • BOLD COLOR DISPLAY ENHANCES ENGAGEMENT WITH ADJUSTABLE SPEED MODES.
BUY & SAVE
PETiB Vibration Noise Electronic Sensor Paranormal Investigation Tool Spirit Box Equipment Ghost Hunting Device EVP Sound Pickup Atmosphere Light with RGB Colors 8
+
ONE MORE?

In Swift, you can determine whether a color is white or black by checking the color values of its components. The color is considered white if all three components (red, green, and blue) are equal to 1.0. Similarly, the color is considered black if all three components are equal to 0.0.

To detect the color, you can access the UIColor object's red, green, and blue properties, which provide the normalized color component values between 0.0 and 1.0.

Here's an example code that demonstrates how to detect if a color is white or black in Swift:

// Create a UIColor object representing the color you want to check let color = UIColor.white

// Get the red, green, and blue components of the color var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 color.getRed(&red, green: &green, blue: &blue, alpha: nil)

// Check if the color is white or black if red == 1.0 && green == 1.0 && blue == 1.0 { print("Color is white") } else if red == 0.0 && green == 0.0 && blue == 0.0 { print("Color is black") } else { print("Color is neither white nor black") }

By using this code snippet, you can determine whether a color is white, black, or neither in Swift based on its RGB components.

How to implement color detection functionality in a Swift app?

To implement color detection functionality in a Swift app, you will need to use the Core Image framework. Here is a step-by-step guide on how to do that:

  1. Import the CoreImage and UIKit frameworks in your Swift file:

import CoreImage import UIKit

  1. Create a function to detect the dominant color:

func detectDominantColor(image: UIImage) -> UIColor? { guard let ciImage = CIImage(image: image) else { return nil }

let colorDetection = CIDetector(ofType: CIDetectorTypeColor, context: nil, options: \[CIDetectorAccuracy: CIDetectorAccuracyHigh\])
let features = colorDetection?.features(in: ciImage)

guard let firstFeature = features?.first as? CIColor else {
    return nil
}

return UIColor(ciColor: firstFeature)

}

  1. Call the detectDominantColor function with an image to detect its dominant color:

if let image = UIImage(named: "your_image_name") { if let dominantColor = detectDominantColor(image: image) { print("Dominant color: \(dominantColor)") // Use dominantColor as needed } }

Note: Make sure to replace "your_image_name" with the name of the image you want to detect the color from. The image should be added to your app's asset catalog.

This code uses the CIDetector class with the CIDetectorTypeColor option to detect colors in a given image. It then retrieves the first detected color and converts it into a UIColor.

Remember to import the necessary image in the asset catalog and ensure that the image is accessible in your project.

How to write a Swift program to verify if a color is white or black?

To write a Swift program to verify if a color is white or black, you can use the UIColor class in the UIKit framework. Here's an example code:

import UIKit

func isColorWhiteOrBlack(color: UIColor) -> Bool { // Convert the color to its RGB representation guard let components = color.cgColor.components else { return false }

// Check if all RGB components are close enough to white or black
let red = components\[0\]
let green = components\[1\]
let blue = components\[2\]

let threshold: CGFloat = 0.1 // Adjust this threshold to your needs

if abs(red - 1) <= threshold && abs(green - 1) <= threshold && abs(blue - 1) <= threshold {
    // Color is close to white
    return true
} else if abs(red) <= threshold && abs(green) <= threshold && abs(blue) <= threshold {
    // Color is close to black
    return true
} else {
    // Color is neither white nor black
    return false
}

}

// Test the function let white = UIColor.white let black = UIColor.black let red = UIColor.red

print(isColorWhiteOrBlack(color: white)) // true print(isColorWhiteOrBlack(color: black)) // true print(isColorWhiteOrBlack(color: red)) // false

This code defines a function isColorWhiteOrBlack that takes a UIColor object as input and returns a boolean value (true if the color is white or black, false otherwise).

The function extracts the RGB components of the color using color.cgColor.components, and checks if these components are close enough to full white (1) or full black (0) based on the provided threshold. Adjusting the threshold allows you to define what is considered "close enough" to white or black.

Finally, the function is tested with white, black, and red colors to verify its correctness.

What is the algorithm to detect black and white colors in Swift?

To detect black and white colors in Swift, you can use the following algorithm:

  1. Convert the color to grayscale: You can do this by calculating the luminance of each pixel. The grayscale value can be obtained by averaging the red, green, and blue components of the color using the formula: gray = (red + green + blue) / 3.
  2. Determine the threshold: Define a threshold value to separate black and white colors. This value can be based on experimentation and can be adjusted to suit your specific needs.
  3. Compare the grayscale value with the threshold: If the grayscale value is below the threshold, classify it as black. If the grayscale value is above the threshold, classify it as white.

Here's a sample code snippet to detect black and white colors in Swift using the above algorithm:

import UIKit

func isBlackOrWhite(color: UIColor, threshold: CGFloat) -> Bool { guard let components = color.cgColor.components else { return false }

let red = components\[0\]
let green = components\[1\]
let blue = components\[2\]

let grayscale = (red + green + blue) / 3

return grayscale <= threshold || grayscale >= (1 - threshold)

}

// Usage let color = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0) // Example color

if isBlackOrWhite(color: color, threshold: 0.1) { print("Color is black or white") } else { print("Color is not black or white") }

In this code, the isBlackOrWhite function takes a UIColor and a threshold value as input. It converts the color to grayscale and then compares the grayscale value with the threshold. If it falls within the threshold range, it returns true indicating that the color is black or white.

Note: This algorithm assumes that the input color is in the RGB color space. If you're working with a different color space, you may need to convert it accordingly before applying the algorithm.

How to handle RGB and grayscale colors when determining if they are white or black in Swift?

In Swift, you can handle RGB and grayscale colors by comparing their respective color components to determine if they are white or black.

For RGB colors:

  1. Obtain the red, green, and blue components of the color using the UIColor method getRed(_:green:blue:alpha:) as shown below:

var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)

  1. If all the red, green, and blue components are close to 1, then the color is considered white. Similarly, if all components are close to 0, the color is considered black. You can set a threshold for this comparison, such as checking if the component is above 0.9 for white, or below 0.1 for black.

For grayscale colors:

  1. Obtain the grayscale component of the color using the UIColor method getWhite(_:alpha:) as shown below:

var white: CGFloat = 0, alpha: CGFloat = 0 color.getWhite(&white, alpha: &alpha)

  1. If the grayscale component is close to 1, then the color is considered white. Similarly, if the component is close to 0, the color is considered black. Again, you can set a threshold to make this comparison.

Here's a sample function that can handle both RGB and grayscale colors to determine if they are white or black:

func isWhiteOrBlack(color: UIColor) -> Bool { var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)

// For RGB color
if red > 0.9 && green > 0.9 && blue > 0.9 {
    return true // Color is white
} else if red < 0.1 && green < 0.1 && blue < 0.1 {
    return true // Color is black
}

// For grayscale color
var white: CGFloat = 0, alpha: CGFloat = 0
color.getWhite(&white, alpha: &alpha)

if white > 0.9 {
    return true // Color is white
} else if white < 0.1 {
    return true // Color is black
}

return false // Color is not pure white or pure black

}

You can then use this function to determine if a color is white or black:

let color = UIColor.white if isWhiteOrBlack(color: color) { print("Color is white or black") }

How to handle cases where a color can be either white or black in Swift?

In Swift, you can handle cases where a color can be either white or black using an enumeration or optionals. Here's how you can approach it:

  1. Enumeration Method: Define a custom enumeration called Color that has cases for white and black: enum Color { case white, black } You can then create variables or constants of type Color to represent the specific color: let whiteColor: Color = .white let blackColor: Color = .black You can now use the Color enumeration to handle the cases where a color can be either white or black.
  2. Optional Method: Use an optional variable to handle cases where the color can be either white or black. Declare a variable of type UIColor? (assuming you are dealing with color using UIColor in Swift) and assign either a UIColor instance or nil to it. var color: UIColor? color = UIColor.white // or color = UIColor.black // or color = nil Later, you can unwrap the optional and handle the cases accordingly, using optional binding or optional chaining: if let unwrappedColor = color { // handle the case when color is not nil } else { // handle the case when color is nil } This allows you to handle situations where color might be either white, black, or even nil.

Choose the method that best suits your specific use case and adjust accordingly.

How to create a function to identify white or black colors in Swift?

You can create a function to identify white or black colors in Swift by checking the RGB or HSB values of the color.

Here is an example implementation using RGB values:

func isWhiteOrBlackColor(color: UIColor) -> Bool { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0

color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)

let threshold: CGFloat = 0.8

if red > threshold && green > threshold && blue > threshold {
    // Color is white
    return true
} else if red < 1 - threshold && green < 1 - threshold && blue < 1 - threshold {
    // Color is black
    return true
} else {
    // Color is neither white nor black
    return false
}

}

// Example usage: let whiteColor = UIColor.white let blackColor = UIColor.black let redColor = UIColor.red

print(isWhiteOrBlackColor(color: whiteColor)) // true print(isWhiteOrBlackColor(color: blackColor)) // true print(isWhiteOrBlackColor(color: redColor)) // false

In this function, we use the getRed(_:green:blue:alpha:) method of UIColor to get the RGB values of the color. We then compare each RGB value to a threshold value (0.8 in this example) to determine if the color is close enough to white or black. If all three RGB values are above the threshold, the color is considered white. If all three RGB values are below 1 minus the threshold, the color is considered black.