裁剪和缩放CGContext – iOS

根据我之前关于裁剪和缩放CMSampleBufferRef的问题 ,我找到了一种方法来修改CMSampleBufferRef中的CGContext,并且我能够使用以下代码绘制CGContext的矩形,路径,圆和清除矩形:

- (void)modifyImage:(CMSampleBufferRef) sampleBuffer { CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); // Lock the image buffer CVPixelBufferLockBaseAddress(imageBuffer,0); // Get information about the image uint8_t *baseAddress = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer); size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); size_t width = CVPixelBufferGetWidth(imageBuffer); size_t height = CVPixelBufferGetHeight(imageBuffer); // Create a CGImageRef from the CVImageBufferRef CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst); CGContextSaveGState(context); CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]); CGContextFillRect(context, CGRectMake(0, 0, 400, 400)); //restore the context and remove the clipping area. CGContextRestoreGState(context); // We unlock the image buffer CVPixelBufferUnlockBaseAddress(imageBuffer,0); // We release some components CGContextRelease(context); CGColorSpaceRelease(colorSpace); return; } 

现在,我想做的是裁剪然后缩放这个CGContext,我尝试使用CGContextClipToRect(context, CGRectMake(0, 0, 360, 640));CGContextScaleCTM(context, 2, 2); 但没有成功。

任何人都可以在这里给我一些建议

创建后,您无法更改CVImageBuffer的尺寸。 如果需要更改尺寸,则必须创建新缓冲区。

如果要裁剪图像,然后将裁剪部分缩放到原始图像的大小,则需要将缩放操作执行到第二个缓冲区,然后从第二个缓冲区复制回第一个缓冲区。