문제

작은 응용 프로그램을 개발하려고합니다. 그것에서, 나는 uiview 내에서 픽셀의 색상을 감지해야합니다. 필요한 픽셀을 정의하는 CGPoint가 있습니다. uiview의 색상은 Coreanimation을 사용하여 변경됩니다.

UIImages에서 색상 정보를 추출하는 복잡한 방법이 있다는 것을 알고 있습니다. 그러나 UIViews를위한 솔루션을 찾을 수 없었습니다.

의사 코드에서 나는 같은 것을 찾고 있습니다

pixel = [view getPixelAtPoint:myPoint];
UIColor *mycolor = [pixel getColor];

모든 입력은 크게 감사했습니다.

도움이 되었습니까?

해결책

꽤 끔찍하고 느립니다. 기본적으로 당신은 당신이 할당하는 백킹 스토어를 사용하여 비트 맵 컨텍스트를 만들어 메모리를 읽을 수있게 한 다음 컨텍스트에서 뷰 레이어를 렌더링하고 RAM의 적절한 지점을 읽습니다.

이미 이미지를 위해 수행하는 방법을 알고 있다면 이미 다음과 같은 작업을 수행 할 수 있습니다.

- (UIImage *)imageForView:(UIView *)view {
  UIGraphicsBeginImageContext(view.frame.size);
  [view.layer renderInContext: UIGraphicsGetCurrentContext()];
  UIImage *retval = UIGraphicsGetImageFromCurrentImageContext(void);
  UIGraphicsEndImageContext();

  return retval;
}

그런 다음 픽셀 데이터를 얻을 수있는 이미지를 얻게됩니다. 이미지를 다루는 메커니즘에는 어쨌든 이미지를 컨텍스트로 렌더링하는 것이 포함되므로이를 병합하고 실제 이미지 생성을 고려할 수 있습니다. 따라서이를 복용하고 이미지를로드하고 컨텍스트 렌더링으로 바꿀 수있는 비트를 제거 할 수 있습니다.

[view.layer renderInContext: UIGraphicsGetCurrentContext()];

당신은 좋을 것입니다.

다른 팁

다음은보다 효율적인 솔루션입니다.

// UIView+ColorOfPoint.h
@interface UIView (ColorOfPoint)
- (UIColor *) colorOfPoint:(CGPoint)point;
@end

// UIView+ColorOfPoint.m
#import "UIView+ColorOfPoint.h"
#import <QuartzCore/QuartzCore.h>

@implementation UIView (ColorOfPoint)

- (UIColor *) colorOfPoint:(CGPoint)point
{
    unsigned char pixel[4] = {0};

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedLast);

    CGContextTranslateCTM(context, -point.x, -point.y);

    [self.layer renderInContext:context];

    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    //NSLog(@"pixel: %d %d %d %d", pixel[0], pixel[1], pixel[2], pixel[3]);

    UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];

    return color;
}

@end

파일 링크 : https://github.com/ivanzoid/ikit/tree/master/uiview+colorofpoint

신속한 버전 이반 조이드대답

스위프트 3

extension CALayer {

    func colorOfPoint(point:CGPoint) -> CGColor {

        var pixel: [CUnsignedChar] = [0, 0, 0, 0]

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)

        let context = CGContext(data: &pixel, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)

        context!.translateBy(x: -point.x, y: -point.y)

        self.render(in: context!)

        let red: CGFloat   = CGFloat(pixel[0]) / 255.0
        let green: CGFloat = CGFloat(pixel[1]) / 255.0
        let blue: CGFloat  = CGFloat(pixel[2]) / 255.0
        let alpha: CGFloat = CGFloat(pixel[3]) / 255.0

        let color = UIColor(red:red, green: green, blue:blue, alpha:alpha)

        return color.cgColor
    }
}

스위프트 2

extension CALayer {

    func colorOfPoint(point:CGPoint)->CGColorRef
    {
        var pixel:[CUnsignedChar] = [0,0,0,0]

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)

        let context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, colorSpace, bitmapInfo.rawValue)

        CGContextTranslateCTM(context, -point.x, -point.y)

        self.renderInContext(context!)

        let red:CGFloat = CGFloat(pixel[0])/255.0
        let green:CGFloat = CGFloat(pixel[1])/255.0
        let blue:CGFloat = CGFloat(pixel[2])/255.0
        let alpha:CGFloat = CGFloat(pixel[3])/255.0

        let color = UIColor(red:red, green: green, blue:blue, alpha:alpha)

        return color.CGColor
    }

}

기본 주변을 기반으로합니다 CALayer 그러나 쉽게 번역 할 수 있습니다 UIView.

사소한 오류를 수정했습니다

- (UIImage *)imageForView:(UIView *)view {
    UIGraphicsBeginImageContext(view.frame.size);
    [view.layer renderInContext: UIGraphicsGetCurrentContext()];
    UIImage *retval = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return retval;
}

또한 추가하십시오

#import <QuartzCore/QuartzCore.h>  

경고 메시지를 피하기 위해 파일에.

코드를 찾은 코드와 결합합니다 여기 완벽하게 작동합니다.

스위프트 4 & 4.2. Xcode 10, iOS 12, Simulator & iPhone 6+를 사용하여 iOS 12.1을 실행합니다.

이 코드는 잘 작동합니다.

extension UIView {
    func colorOfPoint(point: CGPoint) -> UIColor {
        let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)

        var pixelData: [UInt8] = [0, 0, 0, 0]

        let context = CGContext(data: &pixelData, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)

        context!.translateBy(x: -point.x, y: -point.y)

        self.layer.render(in: context!)

        let red: CGFloat = CGFloat(pixelData[0]) / CGFloat(255.0)
        let green: CGFloat = CGFloat(pixelData[1]) / CGFloat(255.0)
        let blue: CGFloat = CGFloat(pixelData[2]) / CGFloat(255.0)
        let alpha: CGFloat = CGFloat(pixelData[3]) / CGFloat(255.0)

        let color: UIColor = UIColor(red: red, green: green, blue: blue, alpha: alpha)

        return color
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top