如何复制 CGBitmapcontext?

How do I copy a CGBitmapcontext?

我正在尝试保存一个位图上下文并将其分配给另一个位图上下文以便稍后能够绘制它。但我不是 100% 确定如何执行此操作。是否可以像下面的示例那样分配它?

//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;
        }

在你的代码中你没有复制上下文,而只是创建一个新的引用,所以在 copybitmap 之后,两个变量将指向同一个对象,并且对一个对象的任何更改会影响对方...

不幸的是,没有直接的方法可以将 CGBitmapContext 复制到另一个 CGBitmapContext 中,因此您需要手动创建第二个,其参数与第一个相同,并使用 memcpy(直接从您的cacheBitmap 如果您有对它的引用,或者从 CGBitmapContextGetData

获取它