2013-03-31 4 views
0

나는이ios에서 픽셀의 사각형을 가져 오는 가장 효율적인 방법은 무엇입니까?

PX, PY =
DX, DY는 = 사각형의 크기를 테스트 할 터치의 위치, 픽셀의 구형의 각 픽셀을 테스트하기 위해 시도하는 다음 코드

UIImage *myImage; // image from which pixels are read 
int ux = px + dx; 
int uy = py + dy; 
for (int x = (px-dx); x <= ux; ++x) 
{ 
    for (int y = (py-dy); y <= uy; ++y) 
    { 
     unsigned char pixelData[] = { 0, 0, 0, 0 }; 
     CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
     CGContextRef context = CGBitmapContextCreate(pixelData, 1, 1, 8, 4, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); 
     CGImageRef cgimage = myImage.CGImage; 
     int imageWidth = CGImageGetWidth(cgimage); 
     int imageHeight = CGImageGetHeight(cgimage); 
     CGContextDrawImage(context, CGRectMake(-px, py - imageHeight, imageWidth, imageHeight), cgimage); 
     CGColorSpaceRelease(colorSpace); 
     CGContextRelease(context); 

     // Here I have latest pixel, with RBG values stored in pixelData that I can test 
    } 
} 

내부 루프의 코드가 위치 x, y의 픽셀을 잡아냅니다. UIImage (myImage)에서 (x-dx, y-dy), (x + dx, y + dy) 픽셀의 전체 사각형을 잡는 더 효율적인 방법이 있습니까?

답변

0

와우, 당신의 대답은 간단합니다.

문제는 당신이 스캔 할 모든 단일 픽셀에 대해 완전히 새로운 비트 맵 컨텍스트 을 생성한다는 것입니다. 하나의 비트 맵 컨텍스트 만 만드는 것은 비용이 많이 들고, 수천 번 연속해서 수행하는 것은 성능면에서 정말로 나쁩니다.

처음에는 하나의 비트 맵 컨텍스트 (사용자 지정 데이터 개체 사용)를 만든 다음 해당 데이터를 스캔하십시오. 방법이 더 빠를거야.

UIImage *myImage; // image from which pixels are read 
CGSize imageSize = [myImage size];  

NSUInteger bytesPerPixel = 4; 
NSUInteger bytesPerRow = bytesPerPixel * imageSize.width; 
NSUInteger bitsPerComponent = 8; 

unsigned char *pixelData = (unsigned char*) calloc(imageSize.height * imageSize.width * bytesPerPixel, sizeof(unsigned char)) 
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
CGContextRef context = CGBitmapContextCreate(pixelData, imageSize.width, 1imageSize.height bitsPerComponent, bytesPerPixel, colorSpace, kCGImageAlphaPremultipliedLast); 
CGContextDrawImage(context, CGRectMake(0, 0, imageSize.width, imageSize.height), myImage.CGImage); 

// you can tweak these 2 for-loops to get whichever section of pixels from the image you want for reading. 

for (NSInteger x = 0; x < imageSize.width; x++) { 

    for (NSInteger y = 0; y < imageSize.height; y++) { 

     int pixelIndex = (bytesPerRow * yy) + xx * bytesPerPixel; 

     CGFloat red = (pixelData[pixelIndex]  * 1.0)/255.0; 
     CGFloat green = (pixelData[pixelIndex + 1] * 1.0)/255.0; 
     CGFloat blue = (pixelData[pixelIndex + 2] * 1.0)/255.0; 
     CGFloat alpha = (pixelData[pixelIndex + 3] * 1.0)/255.0; 
     pixelIndex += 4; 

     UIColor *yourPixelColor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; 

    } 
    } 
} 

// be a good memory citizen 
CGColorSpaceRelease(colorSpace); 
CGContextRelease(context); 
free(pixelData); 
+0

답변과 설명 주셔서 감사하지만 컨텍스트에 이미지를 쓰는 곳이 보이지 않습니까? –

+0

오, 죄송합니다. 이제 해결되었습니다. –

관련 문제