Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,955 questions

51,897 answers

573 users

How to find the average between RGB colors c1 and c2 in Swift

1 Answer

0 votes
import Foundation

struct RGBA {
    let r: Int
    let g: Int
    let b: Int
    let a: Int
}

func averageColor(_ c1: RGBA, _ c2: RGBA) -> RGBA {
    return RGBA(
        r: (c1.r + c2.r) / 2,
        g: (c1.g + c2.g) / 2,
        b: (c1.b + c2.b) / 2,
        a: (c1.a + c2.a) / 2
    )
}

func rgbToHex(r: Int, g: Int, b: Int) -> String {
    return String(format: "#%02X%02X%02X", r, g, b)
}

let color1 = RGBA(r: 255, g: 100, b: 50, a: 255)
let color2 = RGBA(r: 50, g: 170, b: 200, a: 255)

let average = averageColor(color1, color2)
let hex = rgbToHex(r: average.r, g: average.g, b: average.b)

print("Average Color: R=\(average.r), G=\(average.g), B=\(average.b), A=\(average.a)")
print("Average Color (hex): \(hex)")



/*
run:

Average Color: R=152, G=135, B=125, A=255
Average Color (hex): #98877D

*/

 



answered Jun 18, 2025 by avibootz
...