我想知道是否有創建CGImage
對應於上下文中的矩形的方法?從上下文創建子圖像
什麼,我現在在做什麼:
我使用CGBitmapContextCreateImage
創建從上下文CGImage
。然後,我使用CGImageCreateWithImageInRect
來提取該子圖像。
阿尼爾
我想知道是否有創建CGImage
對應於上下文中的矩形的方法?從上下文創建子圖像
什麼,我現在在做什麼:
我使用CGBitmapContextCreateImage
創建從上下文CGImage
。然後,我使用CGImageCreateWithImageInRect
來提取該子圖像。
阿尼爾
試試這個:
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;
}
您可以創建一個裁剪後的圖像所提到here如下,
對於如: -
UIImage *image = //original image
CGRect rect = //cropped rect
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *img = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
您需要從場景中獲得CGImage使用上面的代碼裁剪它。如問題中所述,您可以使用CGBitmapContextCreateImage
。這是the documentation.
我有一個'CGContext'的圖像數據。我想從上下文中的矩形區域創建一個圖像,而不是從'UIImage'內部創建。 –
在這種情況下,你是對的,你需要先創建一個CGImage,然後使用上面的代碼來裁剪它。 – iDev
這似乎是一個很大的開銷。不是嗎?如果你想動態改變上下文(基於觸摸或類似的實時),體驗往往會降低。 –
您可以使用您分配的緩衝區創建CGBitmapContext,並使用相同的緩衝區從頭開始創建CGImage。通過上下文和圖像共享緩衝區,您可以在上下文中繪製圖像,然後使用主圖像的該部分創建CGImage。
請注意,如果您之後繪製到相同的上下文中,裁剪的圖像可能實際上會提取更改(具體取決於多少共享引用 - 而不是內部複製)。根據你在做什麼,你可能會或可能不會覺得這是理想的。
CGImage是不可變的。當您創建一個時,它會創建位圖數據的專用副本。 –
這是一個非常優雅的解決方案,它適用於我的情況!謝謝。 –
第一個函數有一個錯誤。我修好了。大概你在使用第二個功能。 –
我正在使用第一個功能。是的,我看到了錯誤,但主要想法是我借用的。謝謝!但我必須指出一件事。在用戶體驗方面,我沒有看到我之前的實現(如問題中提到的)和這個差別。可能的,瓶頸在別的地方。 –