gpt4 book ai didi

ios - CGbitmapcontext 和 alpha 的问题

转载 作者:行者123 更新时间:2023-11-29 03:00:05 25 4
gpt4 key购买 nike

我正在尝试使用 Core Graphics 开发绘图应用程序。我想让背景处于 alpha 状态,但它是黑色的。我尝试使用所有不同类型的位图信息类型但没有成功。 kCGImageAlphaPremultipliedLast 也不起作用。有人知道如何解决这个问题吗?

- (BOOL) initContext:(CGSize)size {

int bitmapByteCount;
int bitmapBytesPerRow;

// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow = (size.width * 4);
bitmapByteCount = (bitmapBytesPerRow * size.height);

// Allocate memory for image data. This is the destination in memory
// where any drawing to the bitmap context will be rendered.
cacheBitmap = malloc( bitmapByteCount );
if (cacheBitmap == NULL){
return NO;
}

CGBitmapInfo bitmapInfo = kCGImageAlphaNoneSkipFirst;

cacheContext = CGBitmapContextCreate (cacheBitmap, size.width, size.height, 8, bitmapBytesPerRow, CGColorSpaceCreateDeviceRGB(), bitmapInfo);
CGContextSetRGBFillColor(cacheContext, 0, 0, 0, 0);
CGContextFillRect(cacheContext, (CGRect){CGPointZero, size});
return YES;
}

最佳答案

我正在使用这段代码来完成几乎完全符合您要求的工作。我已将颜色设置为红色,alpha 值为 50% 而不是 0%,因此您实际上可以看到 alpha channel 就在那里。

@implementation ViewController
{
CGContextRef cacheContext;
void* cacheBitmap;
__weak IBOutlet UIImageView* _imageView;
}

- (void)viewDidLoad
{
[super viewDidLoad];
}

-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];

[self setupContext:self.view.bounds.size];

CGImageRef cgImage = CGBitmapContextCreateImage(cacheContext);
_imageView.image = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
}


// Name changed to avoid using the magic word "init"
- (BOOL) setupContext:(CGSize)size
{
int bitmapByteCount;
int bitmapBytesPerRow;

// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow = (size.width * 4);
bitmapByteCount = (bitmapBytesPerRow * size.height);

// Allocate memory for image data. This is the destination in memory
// where any drawing to the bitmap context will be rendered.
cacheBitmap = malloc( bitmapByteCount );
if (cacheBitmap == NULL){
return NO;
}

CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrderDefault;

// Create and define the color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

cacheContext = CGBitmapContextCreate (cacheBitmap, size.width, size.height, 8, bitmapBytesPerRow, colorSpace, bitmapInfo);
CGContextSetRGBFillColor(cacheContext, 1., 0, 0, 0.5);
CGContextFillRect(cacheContext, (CGRect){CGPointZero, size});

// Release the color space so memory doesn't leak
CGColorSpaceRelease(colorSpace);

return YES;
}

@end

关于ios - CGbitmapcontext 和 alpha 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23415095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com