Skip to content

Instantly share code, notes, and snippets.

@itfrombit
Last active Nov 4, 2018
Embed
What would you like to do?
Bit Blitting with CGLayer
- (void)drawRect:(NSRect)dirtyRect
{
[super drawRect:dirtyRect];
static int redOffset = 0;
static int greenOffset = 0;
static int blueOffset = 0;
for (int y = 0; y < _bitmapHeight; y++)
{
for (int x = 0; x < _bitmapWidth; x++)
{
unsigned char* pixel = _pixels + (y * _bitmapWidth + x) * _bitmapComponents;
pixel[0] = x + y + redOffset; // red
pixel[1] = y + greenOffset;
pixel[2] = x + blueOffset;
pixel[3] = x + y + redOffset;
}
}
++redOffset;
++greenOffset;
++blueOffset;
CGContextRef gctx = [[NSGraphicsContext currentContext] graphicsPort];
CGRect layerRect = [self bounds];
CGLayerRef layer = CGLayerCreateWithContext(gctx, layerRect.size, NULL);
CGContextRef lctx = CGLayerGetContext(layer);
CMProfileRef prof;
CMGetSystemProfile(&prof);
_colorSpace = CGColorSpaceCreateWithPlatformColorSpace(prof);
CMCloseProfile(prof);
_bitmapContext = CGBitmapContextCreate(_pixels, _bitmapWidth, _bitmapHeight,
_bitmapBitsPerComponent, _bitmapBytesPerRow,
_colorSpace, _bitmapInfo);
_bitmapImageRef = CGBitmapContextCreateImage(_bitmapContext);
CGContextSetInterpolationQuality(_bitmapContext, kCGInterpolationNone);
CGContextDrawImage(lctx, layerRect, _bitmapImageRef);
CGContextSaveGState(gctx);
CGContextDrawLayerAtPoint(gctx, CGPointZero, layer);
CGContextRestoreGState(gctx);
CGColorSpaceRelease(_colorSpace);
CGImageRelease(_bitmapImageRef);
CGContextRelease(_bitmapContext);
CGLayerRelease(layer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment