Last active
November 4, 2018 16:43
-
-
Save itfrombit/909b6ee24f31a2746267 to your computer and use it in GitHub Desktop.
Bit Blitting with CGLayer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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