2012-01-24 5 views
0

색상 및 알파 (불투명 및 투명 픽셀)의 두 가지 유형의 픽셀이있는 마스킹 CGContext이 있습니다. 내 맥락에서 알파 픽셀의 비율을 계산하는 방법?CGContext의 알파 픽셀 수

답변

3

나는 그것을 테스트하지 못했지만,이 트릭을해야한다 - 단지 ReportAlphaPercent에게 CGImageRef 통과 : 그것은 작동

UIImage *foo; //The image you want to analyze 
float alphaPercent = ReportAlphaPercent(foo.CGImage); 


float ReportAlphaPercent(CGImageRef imgRef) 
{ 
    size_t w = CGImageGetWidth(imgRef); 
    size_t h = CGImageGetHeight(imgRef); 

    unsigned char *inImage = malloc(w * h * 4); 
    memset(inImage, 0, (h * w * 4)); 

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    CGContextRef context = CGBitmapContextCreate(inImage, w, h, 8, w * 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); 
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh); 
    CGContextSetShouldAntialias(context, NO); 
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), imgRef); 

    int byteIndex = 0; 

    int alphaCount = 0; 

    for(int i = 0; i < (w * h); i++) { 

     if (inImage[byteIndex + 3]) { // if the alpha value is not 0, count it 
      alphaCount++; 
     } 

     byteIndex += 4; 
    } 

    free(inImage); 

    CGContextRelease(context); 
    CGColorSpaceRelease(colorSpace); 

    return (float) alphaCount/(w * h); 
} 
+0

을! Jeshua에게 감사드립니다! – andr111