Skip to content

Instantly share code, notes, and snippets.

@itfrombit
Last active November 4, 2018 16:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itfrombit/909b6ee24f31a2746267 to your computer and use it in GitHub Desktop.
Save itfrombit/909b6ee24f31a2746267 to your computer and use it in GitHub Desktop.
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