使用掩码获取图像像素



我有一些原始图像。

我需要使用特定的蒙版获取和显示此图像的某些部分。遮罩不是矩形或形状。它包含不同的多边形和形状。

是否有任何方法或教程如何实现?或者从哪里开始?我应该写一些小的着色器或比较合适的图像像素或类似的东西吗?

如有任何建议,我将很高兴。

谢谢

你可以把你的图像放到UIImageView中然后给图像视图添加一个蒙版比如

myImageView.layer.mask = myMaskLayer;

要绘制自定义形状,myMaskLayer应该是实现drawInContext方法的CALayer的子类的实例。该方法应该用全alpha绘制要在图像中显示的区域,并用零alpha绘制要隐藏的区域(如果您喜欢,也可以在alpha之间使用)。下面是一个CALayer子类的示例实现,当在图像视图上用作遮罩时,将只显示图像左上角的椭圆形区域:

@interface MyMaskLayer : CALayer
@end
@implementation MyMaskLayer
- (void)drawInContext:(CGContextRef)ctx {
    static CGColorSpaceRef rgbColorSpace;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    });
    const CGRect selfBounds = self.bounds;
    CGContextSetFillColorSpace(ctx, rgbColorSpace);
    CGContextSetFillColor(ctx, (CGFloat[4]){0.0, 0.0, 0.0, 0.0});
    CGContextFillRect(ctx, selfBounds);
    CGContextSetFillColor(ctx, (CGFloat[4]){0.0, 0.0, 0.0, 1.0});
    CGContextFillEllipseInRect(ctx, selfBounds);
}
@end

要将这样的蒙版层应用于图像视图,可以使用如下代码

MyMaskLayer *maskLayer = [[MyMaskLayer alloc] init];
maskLayer.bounds = self.view.bounds;
[maskLayer setNeedsDisplay];
self.imageView.layer.mask = maskLayer;

现在,如果你想从这样的渲染中获得像素数据,最好渲染到一个由位图支持的CGContext中,你可以在其中控制像素缓冲区。您可以在渲染后检查缓冲区中的像素数据。下面是一个例子,我创建了一个位图上下文,并在这个位图上下文中渲染一个图层和蒙版。因为我为像素数据提供了自己的缓冲区,所以我可以在渲染后在缓冲区中摸索以获得RGBA值。

const CGRect imageViewBounds = self.imageView.bounds;
const size_t imageWidth = CGRectGetWidth(imageViewBounds);
const size_t imageHeight = CGRectGetHeight(imageViewBounds);
const size_t bytesPerPixel = 4;
// Allocate your own buffer for the bitmap data.  You can pass NULL to
// CGBitmapContextCreate and then Quartz will allocate the memory for you, but
// you won't have a pointer to the resulting pixel data you want to inspect!
unsigned char *bitmapData = (unsigned char *)malloc(imageWidth * imageHeight * bytesPerPixel);
CGContextRef context = CGBitmapContextCreate(bitmapData, imageWidth, imageHeight, 8, bytesPerPixel * imageWidth, rgbColorSpace, kCGImageAlphaPremultipliedLast);
// Render the image into the bitmap context.
[self.imageView.layer renderInContext:context];
// Set the blend mode to destination in, pixels become "destination * source alpha"
CGContextSetBlendMode(context, kCGBlendModeDestinationIn);
// Render the mask into the bitmap context.
[self.imageView.layer.mask renderInContext:context];
// Whatever you like here, I just chose the middle of the image.
const size_t x = imageWidth / 2;
const size_t y = imageHeight / 2;
const size_t pixelIndex = y * imageWidth + x;
const unsigned char red = bitmapData[pixelIndex];
const unsigned char green = bitmapData[pixelIndex + 1];
const unsigned char blue = bitmapData[pixelIndex + 2];
const unsigned char alpha = bitmapData[pixelIndex + 3];
NSLog(@"rgba: {%u, %u, %u, %u}", red, green, blue, alpha);

最新更新