2

i 'm trying to get the effect that apple's music app have , you've noticed that the text color is always stays readable no matter what is in background, for example : enter image description here see that green color on black background...

i just want to make my text lighter(white) or darker(black) (according to background image's color )

how can i do this ??

yeah thats true similar questions were asked here before and i checked them too

here's what i got

this questions answer says to get the average color of image then see if image is darker or lighter and accordingly change the text color

but that question is based on Obj C and also the way for getting the average color is in Obj C

so how can i do this in swift ??

Community
  • 1
  • 1
remy boys
  • 2,928
  • 5
  • 36
  • 65

1 Answers1

1

Objective-C and Swift are quite easily convertible between themselves. I'd strongly encourage you to practice this in your spare time, as there are a lot of good iOS code samples/tutorials based on Objective-C, and the SDK is the same so it is worth a while.

As to the problem at hand, you can get color components like this in Swift :

let color = UIColor(red: 0.12, green: 0.12, blue: 0.12, alpha: 1)
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 = 105/255
let bgDelta = ((red * 0.299) + (green * 0.587) + (blue * 0.114))

let textColor = ((1 - bgDelta) < threshold) ? UIColor.blackColor() : UIColor.whiteColor()

As to finding the average color first, you can use this pod. It is written in Objective-C, but both Swift and Obj-C can be mixed in a single project, and cocoa pods sets it up for you. If you haven't used cocoa pods yet, there are lots of good tutorials on how to start, including on their site.

Losiowaty
  • 7,911
  • 2
  • 32
  • 47
  • hey man thanks for responding , and i'll keep your suggestion on mind , however the above function is always retuning `UIDeviceWhiteColorSpace 1 1` is it expected behavior ? i tried this on different colors still the out put is same – remy boys Sep 08 '16 at 08:48