태그 보관물: uicolor

uicolor

UIColor가 어둡거나 밝은 지 확인하십시오. CGFloat colorBrightness

선택한 UIColor (사용자가 선택한)가 어둡거나 밝은 지 여부를 확인해야하므로 가독성을 높이기 위해 해당 색상 위에있는 텍스트 줄의 색상을 변경할 수 있습니다.

다음은 Flash / Actionscript (데모 포함)의 예입니다.
http://web.archive.org/web/20100102024448/http://theflashblog.com/?p=173

이견있는 사람?

건배, 안드레

최신 정보

모든 사람의 제안 덕분에 다음은 작동 코드입니다.

- (void) updateColor:(UIColor *) newColor
{
    const CGFloat *componentColors = CGColorGetComponents(newColor.CGColor);

    CGFloat colorBrightness = ((componentColors[0] * 299) + (componentColors[1] * 587) + (componentColors[2] * 114)) / 1000;
    if (colorBrightness < 0.5)
    {
        NSLog(@"my color is dark");
    }
    else
    {
        NSLog(@"my color is light");
    }
}

다시 한번 감사합니다 🙂



답변

W3C에는 다음이 있습니다.
http://www.w3.org/WAI/ER/WD-AERT/#color-contrast

흑백 텍스트 만 수행하는 경우 위의 색상 밝기 계산을 사용하십시오. 125 미만이면 흰색 텍스트를 사용하십시오. 125 이상이면 검정색 텍스트를 사용하십시오.

편집 1 : 검정 텍스트쪽으로 편향. 🙂

편집 2 : 사용할 공식은 ((빨간색 값 * 299) + (녹색 값 * 587) + (파란색 값 * 114)) / 1000입니다.


답변

다음은이 검사를 수행하는 Swift (3) 확장입니다.

이 확장은 그레이 스케일 색상으로 작동합니다. 그러나, 당신은 RGB 초기화에 모든 색상을 생성하고 사용하지 않는 경우와 같은 색상으로 구축 UIColor.black하고 UIColor.white, 다음 아마도 당신은 추가 검사를 제거 할 수 있습니다.

extension UIColor {

    // Check if the color is light or dark, as defined by the injected lightness threshold.
    // Some people report that 0.7 is best. I suggest to find out for yourself.
    // A nil value is returned if the lightness couldn't be determined.
    func isLight(threshold: Float = 0.5) -> Bool? {
        let originalCGColor = self.cgColor

        // Now we need to convert it to the RGB colorspace. UIColor.white / UIColor.black are greyscale and not RGB.
        // If you don't do this then you will crash when accessing components index 2 below when evaluating greyscale colors.
        let RGBCGColor = originalCGColor.converted(to: CGColorSpaceCreateDeviceRGB(), intent: .defaultIntent, options: nil)
        guard let components = RGBCGColor?.components else {
            return nil
        }
        guard components.count >= 3 else {
            return nil
        }

        let brightness = Float(((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000)
        return (brightness > threshold)
    }
}

테스트 :

func testItWorks() {
    XCTAssertTrue(UIColor.yellow.isLight()!, "Yellow is LIGHT")
    XCTAssertFalse(UIColor.black.isLight()!, "Black is DARK")
    XCTAssertTrue(UIColor.white.isLight()!, "White is LIGHT")
    XCTAssertFalse(UIColor.red.isLight()!, "Red is DARK")
}

참고 : Swift 3 12/7/18로 업데이트 됨


답변

Erik Nedwidek의 답변을 사용하여 쉽게 포함 할 수있는 코드 조각을 만들었습니다.

- (UIColor *)readableForegroundColorForBackgroundColor:(UIColor*)backgroundColor {
    size_t count = CGColorGetNumberOfComponents(backgroundColor.CGColor);
    const CGFloat *componentColors = CGColorGetComponents(backgroundColor.CGColor);

    CGFloat darknessScore = 0;
    if (count == 2) {
        darknessScore = (((componentColors[0]*255) * 299) + ((componentColors[0]*255) * 587) + ((componentColors[0]*255) * 114)) / 1000;
    } else if (count == 4) {
        darknessScore = (((componentColors[0]*255) * 299) + ((componentColors[1]*255) * 587) + ((componentColors[2]*255) * 114)) / 1000;
    }

    if (darknessScore >= 125) {
        return [UIColor blackColor];
    }

    return [UIColor whiteColor];
}


답변

Swift3

extension UIColor {
    var isLight: Bool {
        var white: CGFloat = 0
        getWhite(&white, alpha: nil)
        return white > 0.5
    }
}

// Usage
if color.isLight {
    label.textColor = UIColor.black
} else {
    label.textColor = UIColor.white
}


답변

Swift 4 버전

extension UIColor {
    func isLight() -> Bool {
        guard let components = cgColor.components, components.count > 2 else {return false}
        let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000
        return (brightness > 0.5)
    }
}


답변

범주 에서이 문제에 대한 나의 해결책 (여기에 다른 답변에서 가져옴). 또한 회색조 색상으로 작동하며 작성 당시에는 다른 답변이 없습니다.

@interface UIColor (Ext)

    - (BOOL) colorIsLight;

@end

@implementation UIColor (Ext)

    - (BOOL) colorIsLight {
        CGFloat colorBrightness = 0;

        CGColorSpaceRef colorSpace = CGColorGetColorSpace(self.CGColor);
        CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);

        if(colorSpaceModel == kCGColorSpaceModelRGB){
            const CGFloat *componentColors = CGColorGetComponents(self.CGColor);

            colorBrightness = ((componentColors[0] * 299) + (componentColors[1] * 587) + (componentColors[2] * 114)) / 1000;
        } else {
            [self getWhite:&colorBrightness alpha:0];
        }

        return (colorBrightness >= .5f);
    }

@end


답변

더 간단한 Swift 3 확장 :

extension UIColor {
    func isLight() -> Bool {
        guard let components = cgColor.components else { return false }
        let redBrightness = components[0] * 299
        let greenBrightness = components[1] * 587
        let blueBrightness = components[2] * 114
        let brightness = (redBrightness + greenBrightness + blueBrightness) / 1000
        return brightness > 0.5
    }
}