OGeek|极客世界-中国程序员成长平台

标题: ios - 从上下文创建子图像 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 23:53
标题: ios - 从上下文创建子图像

我想知道是否有办法创建一个 CGImage 对应于上下文中的一个矩形?

我现在在做什么:

我正在使用 CGBitmapContextCreateImage 从上下文创建 CGImage。然后,我使用 CGImageCreateWithImageInRect 来提取该子图像。

阿尼尔



Best Answer-推荐答案


试试这个:

static CGImageRef createImageWithSectionOfBitmapContext(CGContextRef bigContext,
    size_t x, size_t y, size_t width, size_t height)
{
    uint8_t *data = CGBitmapContextGetData(bigContext);
    size_t bytesPerRow = CGBitmapContextGetBytesPerRow(bigContext);
    size_t bytesPerPixel = CGBitmapContextGetBitsPerPixel(bigContext) / 8;
    data += x * bytesPerPixel + y * bytesPerRow;
    CGContextRef smallContext = CGBitmapContextCreate(data,
        width, height,
        CGBitmapContextGetBitsPerComponent(bigContext), bytesPerRow,
        CGBitmapContextGetColorSpace(bigContext),
        CGBitmapContextGetBitmapInfo(bigContext));
    CGImageRef image = CGBitmapContextCreateImage(smallContext);
    CGContextRelease(smallContext);
    return image;
}

或者这个:

static CGImageRef createImageWithSectionOfBitmapContext(CGContextRef bigContext,
    size_t x, size_t y, size_t width, size_t height)
{
    uint8_t *data = CGBitmapContextGetData(bigContext);
    size_t bytesPerRow = CGBitmapContextGetBytesPerRow(bigContext);
    size_t bytesPerPixel = CGBitmapContextGetBitsPerPixel(bigContext) / 8;
    data += x * bytesPerPixel + y * bytesPerRow;
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, data,
        height * bytesPerRow, NULL);
    CGImageRef image = CGImageCreate(width, height,
        CGBitmapContextGetBitsPerComponent(bigContext),
        CGBitmapContextGetBitsPerPixel(bigContext),
        CGBitmapContextGetBytesPerRow(bigContext),
        CGBitmapContextGetColorSpace(bigContext),
        CGBitmapContextGetBitmapInfo(bigContext),
        provider, NULL, NO, kCGRenderingIntentDefault);
    CGDataProviderRelease(provider);
    return image;
}

关于ios - 从上下文创建子图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13664259/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4