本文介绍了裁剪和缩放CGContext-iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在上一个关于的问题之后,我发现一种修改CMSampleBufferRef内的CGContext的方法,我可以使用以下代码绘制CGContext的矩形,路径,圆形和空白矩形:

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

现在,我要做的是裁剪然后缩放此CGContext,我尝试使用 CGContextClipToRect(context,CGRectMake(0,0,360,640)); CGContextScaleCTM(context,2,2);

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

推荐答案

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

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.

这篇关于裁剪和缩放CGContext-iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 21:54