简体   繁体   English

在iOS上的图像中查找非透明填充的CGRect

[英]Finding non transparent filled CGRect in images on iOS

I've some images on my iOS application which is partially transparent (format is PNG). 我的iOS应用程序中有一些图像是部分透明的(格式为PNG)。

Can i find CGRect areas of non-transparent areas on an image? 我可以在图像上找到不透明区域的CGRect区域吗?

应用预览

I am not aware of any function that would give this out of the box. 我不知道有什么功能可以立即使用。 But you can write your own function. 但是您可以编写自己的函数。 All you need to do is to get the color of pixels one by one and figure out if they make a rect or not. 您需要做的就是逐一获得像素的颜色,并弄清它们是否为矩形。

To get this you can use the following code. 为此,您可以使用以下代码。

CGImageRef image = [myUIImage CGImage];
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);

CGContextDrawImage(context, CGRectMake(0, 0, width, height));
CGContextRelease(context);

// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
red = rawData[byteIndex];
green = rawData[byteIndex + 1];
blue = rawData[byteIndex + 2];
alpha = rawData[byteIndex + 3];

This was originally posted at this question. 这最初发布于此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM