Reputation: 820
I'm trying to save a bitmap context and assigning it to another bitmap context to be able to draw it later on. But i'm not 100 % sure how to do this. Is it possible to just assign it like the example below?
//paint.h
CGContextRef cachecontext;
CGContextRef cachecontexttoSaveOn;
//paint.m
-(void)copybitmap{
cachecontexttoSaveOn = cachecontext;
}
- (BOOL) initContext:(CGSize)size {
scaleFactor = [[UIScreen mainScreen] scale];
// scaleFactor = 1;
//non-retina
// scalefactor = 2; retina
int bitmapBytesPerRow;
// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow = (size.width * 4*scaleFactor);
bitmapByteCount = (bitmapBytesPerRow * (size.height*scaleFactor));
// Allocate memory for image data. This is the destination in memory
// where any drawing to the bitmap context will be rendered.
cacheBitmap = malloc( bitmapByteCount );
smallbyte = 100 * 4*scaleFactor * 100 *scaleFactor;
copiedBitmap = malloc(smallbyte);
if (cacheBitmap == NULL){
return NO;
}
CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little;
colorSpace = CGColorSpaceCreateDeviceRGB();
cacheContext = CGBitmapContextCreate (cacheBitmap, size.width*scaleFactor, size.height *scaleFactor, 8, bitmapBytesPerRow, colorSpace, bitmapInfo);
CGContextScaleCTM(cacheContext, scaleFactor, scaleFactor);
CGColorSpaceRelease(colorSpace);
CGContextSetRGBFillColor(cacheContext, 0, 0, 0, 0.0);
CGContextFillRect(cacheContext, (CGRect){CGPointZero, CGSizeMake(size.height*scaleFactor, size.width*scaleFactor)});
// path = CGPathCreateMutable();
return YES;
}
Upvotes: 1
Views: 375
Reputation: 2616
In your code you are not copying the context, but simply creating a new reference to it, so after copybitmap both variables will point to the same object and any change to one will affect the other...
Unfortunately there's no direct way to copy a CGBitmapContext into another one, so you'll need to manually create a second one with the same parameters as the first, and a copy of the backing data with memcpy (directly from your cacheBitmap if you have a reference to it, or getting it from CGBitmapContextGetData
Upvotes: 2