问题
Following from my previous question about Crop and Scale CMSampleBufferRef, I found a way to modify the CGContext inside that CMSampleBufferRef and I am able to draw rectangle, path, circle and clear rect of the CGContext, using the following code:
- (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;
}
Now, what I want to do is to crop and then scale this CGContext, I tried with CGContextClipToRect(context, CGRectMake(0, 0, 360, 640));
and CGContextScaleCTM(context, 2, 2);
but not successful.
Can anyone gives me some more advices here
回答1:
You cannot change the dimensions of a CVImageBuffer after creation. If you need to change the dimensions, you must create a new buffer.
If you want to crop the image, and then scale the cropped portion up to the size of the original image, you need to perform the scaling operation into a second buffer and then copy from the second buffer back to the first buffer.
来源:https://stackoverflow.com/questions/8501149/crop-and-scale-cgcontext-ios