如何复制CGBitmapcontext?

时间:2015-01-03 21:26:54

标签: objective-c bitmap core-graphics

我正在尝试保存位图上下文并将其分配给另一个位图上下文,以便稍后能够绘制它。但我不是百分百肯定如何做到这一点。是否可以像下面的示例一样分配它?

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

1 个答案:

答案 0 :(得分:2)

在您的代码中,您不是要复制上下文,而只是创建一个新的引用,因此在 copybitmap 之后,两个变量都将指向同一个对象,对一个变量的任何更改都会影响另一个。 ..

不幸的是没有直接的方法将CGBitmapContext复制到另一个,所以你需要手动创建第二个与第一个相同的参数,以及带有memcpy的后备数据的副本(直接来自你的 cacheBitmap 如果您有引用它,或从 CGBitmapContextGetData

获取它