Programing

UIColor에서 RGB 값을 얻는 방법은 무엇입니까?

lottogame 2020. 8. 29. 11:48
반응형

UIColor에서 RGB 값을 얻는 방법은 무엇입니까?


다음 코드를 사용하여 색상 개체를 만들고 있습니다.

curView.backgroundColor = [[UIColor alloc] initWithHue:229 saturation:40 brightness:75 alpha:1];

생성 된 색상 개체에서 RGB 값을 검색하려면 어떻게해야합니까?


const CGFloat *colors = CGColorGetComponents( curView.backgroundColor.CGColor );

다음 링크는 추가 세부 정보를 제공합니다.


iOS 5에서는 다음을 사용할 수 있습니다.

CGFloat red = 0.0, green = 0.0, blue = 0.0, alpha =0.0;
[multipliedColor getRed:&red green:&green blue:&blue alpha:&alpha];

SWIFT 3 및 4

cgColor.components가 항상 4 가지 색상 값을 반환하는 것은 아니므로 CIColor 래퍼에서 가져 오도록 변경했습니다.

extension UIColor {
    var redValue: CGFloat{ return CIColor(color: self).red }
    var greenValue: CGFloat{ return CIColor(color: self).green }
    var blueValue: CGFloat{ return CIColor(color: self).blue }
    var alphaValue: CGFloat{ return CIColor(color: self).alpha }
}

SWIFT 2

extension UIColor {
    var red: CGFloat{ return CGColorGetComponents(self.CGColor)[0] }
    var green: CGFloat{ return CGColorGetComponents(self.CGColor)[1] }
    var blue: CGFloat{ return CGColorGetComponents(self.CGColor)[2] }
    var alpha: CGFloat{ return CGColorGetComponents(self.CGColor)[3] }
}

가장 효율적인 방법은 아니므로 뷰가 지속적으로 다시 그려지는 곳에 이것을 사용하지 않을 것입니다.


도움이 되었기를 바랍니다.

CGFloat red, green, blue, alpha;

//Create a sample color

UIColor *redColor = [UIColor redColor];

//Call 

[redColor getRed: &red 
  green: &green
  blue: &blue 
  alpha: &alpha];
NSLog(@"red = %f. Green = %f. Blue = %f. Alpha = %f",
  red,
  green,
  blue,
  alpha);

이것에 대한 카테고리를 만들었습니다.

NSLog(@"%f", [UIColor blueColor].blue); // 1.000000

다음과 같이 진행됩니다.

typedef enum { R, G, B, A } UIColorComponentIndices;

@implementation UIColor (EPPZKit)

-(CGFloat)red
{ return CGColorGetComponents(self.CGColor)[R]; }

-(CGFloat)green
{ return CGColorGetComponents(self.CGColor)[G]; }

-(CGFloat)blue
{ return CGColorGetComponents(self.CGColor)[B]; }

-(CGFloat)alpha
{ return CGColorGetComponents(self.CGColor)[A]; }

@end

eppz!kit더 많은 UIColor 혜택있는 부분입니다 .


const float* colors = CGColorGetComponents( curView.backgroundColor.CGColor );

감사. const경고를 생성 할 때 줄 시작 부분에 를 추가해야 했습니다.


 UIColor *color = [[UIColor greenColor] retain]; //line 1

//OR(You will have color variable either like line 1 or line 2)

color = curView.backgroundColor;//line 2
CGColorRef colorRef = [color CGColor];

int _countComponents = CGColorGetNumberOfComponents(colorRef);

if (_countComponents == 4) {
    const CGFloat *_components = CGColorGetComponents(colorRef);
    CGFloat red     = _components[0];
    CGFloat green = _components[1];
    CGFloat blue   = _components[2];
    CGFloat alpha = _components[3];

    NSLog(@"%f,%f,%f,%f",red,green,blue,alpha);
}

[color release];

David Rees의 Swift 3 버전 답변 :

extension UIColor {

    var redValue: CGFloat{
        return cgColor.components! [0]
    }

    var greenValue: CGFloat{
        return cgColor.components! [1]
    }

    var blueValue: CGFloat{
        return cgColor.components! [2]
    }

    var alphaValue: CGFloat{
        return cgColor.components! [3]
    }
}

iOS 2.0부터는 RGB 공간 밖에있는 whiteColor와 같은 색상의 경우에도 색상의 RGB 또는 RGBA 문자열 표현을 반환하는 UIColorcalled 에 private 인스턴스 메서드가 styleString있습니다.

목표 -C :

@interface UIColor (Private)

- (NSString *)styleString;

@end

// ...

[[UIColor whiteColor] styleString]; // rgb(255,255,255)
[[UIColor redColor] styleString]; // rgb(255,0,0)
[[UIColor lightTextColor] styleString]; // rgba(255,255,255,0.600000)

Swift에서는 브리징 헤더를 사용하여 인터페이스를 노출 할 수 있습니다. 순수한 Swift를 사용 @objc하면 private 메서드와 프로토콜 을 사용하여 프로토콜 을 만들어야 unsafeBitCast UIColor합니다.

@objc protocol  UIColorPrivate {
    func styleString() -> String
}

let white = UIColor.whiteColor()
let red = UIColor.redColor()
let lightTextColor = UIColor.lightTextColor()

let whitePrivate = unsafeBitCast(white, UIColorPrivate.self)
let redPrivate = unsafeBitCast(red, UIColorPrivate.self)
let lightTextColorPrivate = unsafeBitCast(lightTextColor, UIColorPrivate.self)

whitePrivate.styleString() // rgb(255,255,255)
redPrivate.styleString() // rgb(255,0,0)
lightTextColorPrivate.styleString() // rgba(255,255,255,0.600000)

UITableViewStyle"UITableViewStyleGrouped"의 배경색을 얻고 싶었 으므로 viewDidAppear:메서드에 코드를 추가했습니다.

NSLog(@"%@", self.tableView.backgroundView.backgroundColor);

예상 한대로 로그를 반환했습니다.

UIDeviceRGBColorSpace 0.937255 0.937255 0.956863 1

간단히 말해서 NSLog(@"%@", [UIColor whateverColor]);


HandyUIKit사용 하면이 작업이 정말 쉬워집니다 .

import HandyUIKit    

let color = UIColor(red: 0.1, green: 0.2, blue: 0.3, alpha: 0.4)

// get any of the rgba values
color.rgba.red    // => 0.1
color.rgba.green  // => 0.2
color.rgba.blue   // => 0.3
color.rgba.alpha  // => 0.4

가져 오는hsba 유사한 옵션도 있습니다 .

let color = UIColor(hue: 0.1, saturation: 0.2, brightness: 0.3, alpha: 0.4)

// you can get any of the hsba values, too
color.hsba.hue         // => 0.1
color.hsba.saturation  // => 0.2
color.hsba.brightness  // => 0.3
color.hsba.alpha       // => 0.4

Simply install it using Carthage and you're good to go.

I hope it helps!


Some useful macros I've made for this and other color controls:

In your case you would just use

getRGBA(myColor, red, green, blue, alpha);

NSLog(@"Red Value: %f", red);
NSLog(@"Blue Value: %f", green);
NSLog(@"Green Value: %f", blue);

Macros:

#define rgba(r,g,b,a) [UIColor colorWithRed:((float)(r))/255.0f green:((float)(g))/255.0f blue:((float)(b))/255.0f alpha:a]
#define rgb(r,g,b) rgba(r, g, b, 1.0f)

#define rgbaf(r,g,b,a) [UIColor colorWithRed:(r) green:(g) blue:(b) alpha:a]
#define rgbf(r,g,b) rgbaf(r, g, b, 1.0f)

#define rgba_fromColor(__color, __r, __g, __b, __a) \
CGFloat __r, __g, __b, __a;\
UIColor *__unpackedColor = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:__color]];/*Bring system colors into compatible color-space (e.g. DarkGrayColor)*/\
[__unpackedColor getRed:&__r green:&__g blue:&__b alpha:&__a];
#define getRGBA(__color, __r, __g, __b, __a) hsba_fromColor(__color, __r, __g, __b, __a)

#define getRed(__color)  (\
(^float (void){\
rgba_fromColor(__color, r, g, b, a);\
return r;\
})()\
)

#define getGreen(__color)  (\
(^float (void){\
rgba_fromColor(__color, r, g, b, a);\
return g;\
})()\
)

#define getBlue(__color)  (\
(^float (void){\
rgba_fromColor(__color, r, g, b, a);\
return b;\
})()\
)

#define getAlpha(__color)  (\
(^float (void){\
rgba_fromColor(__color, r, g, b, a);\
return a;\
})()\
)










#define hsba(h,s,b,a) [UIColor colorWithHue:((float)(h))/360.0f saturation:((float)(s))/100.0f brightness:((float)(b))/100.0f alpha:a]
#define hsb(h,s,b) hsba(h, s, b, 1.0f)

#define hsbaf(h,s,b,a) [UIColor colorWithHue:(h) saturation:(s) brightness:(b) alpha:a]
#define hsbf(h,s,b) rgbaf(h, s, b, 1.0f)

#define hsba_fromColor(__color, __h, __s, __b, __a) \
CGFloat __h, __s, __b, __a;\
UIColor *__unpackedColor = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:__color]];/*Bring system colors into compatible color-space (e.g. DarkGrayColor)*/\
[__unpackedColor getHue:&__h saturation:&__s brightness:&__b alpha:&__a];
#define getHSBA(__color, __h, __s, __b, __a) rgba_fromColor(__color, __h, __s, __b, __a)

#define getHue(__color)  (\
(^float (void){\
hsba_fromColor(__color, h, s, b, a);\
return h;\
})()\
)

#define getSaturation(__color)  (\
(^float (void){\
hsba_fromColor(__color, h, s, b, a);\
return s;\
})()\
)

#define getBrightness(__color)  (\
(^float (void){\
hsba_fromColor(__color, h, s, b, a);\
return b;\
})()\
)

/*
///already defined in RGBA macros
#define getAlpha(__color)  (\
(^float (void){\
hsba_fromColor(__color, h, s, b, a);\
return a;\
})()\
)
*/

The top voted answer is outdated:

error: :3:1: error: 'CGColorGetComponents' has been replaced by property 'CGColor.components'

Instead, use

myUIColor.cgColor.components


set your UIColor like this

UIColor.FromRGB(128, 179, 255)

this is for Xamarin ios... but for sure there is a method like this in swift.

참고URL : https://stackoverflow.com/questions/437113/how-to-get-rgb-values-from-uicolor

반응형