gpt4 book ai didi

objective-c - 如何使PNG变暗?

转载 作者:搜寻专家 更新时间:2023-10-30 20:06:42 24 4
gpt4 key购买 nike

我可能会指出 Objective-C 中的绘图和渲染是我的弱项。现在,这是我的问题。

我想在我的游戏中添加“日/夜”功能。它在 map 上有很多对象。每个对象都是一个 UIView,其中包含变量中的一些数据和一些 UIImageView: Sprite ,并且一些对象有一个隐藏环(用于显示选择)。

我希望能够使 UIView 的内容变暗,但我不知道该怎么做。 Sprite 是具有透明度的 PNG。我刚刚设法使用以下方法在 Sprite 后面添加了一个黑色矩形:

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);

CGContextSetRGBFillColor(ctx, 0, 0, 0, 0.5);
CGContextFillRect(ctx, rect);
CGContextRestoreGState(ctx);

据我所知,这应该在 drawRect 方法中完成。请帮忙!

如果您想更好地理解我的场景,我尝试执行此操作的应用程序在 App Store 中称为“Kipos”。

最佳答案

Floris497 的方法是一种很好的策略,可以一次对多个图像进行整体变暗(在这种情况下可能更多)。但这是生成较暗 UIImages 的通用方法(同时尊重 alpha 像素):

+ (UIImage *)darkenImage:(UIImage *)image toLevel:(CGFloat)level
{
// Create a temporary view to act as a darkening layer
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
UIView *tempView = [[UIView alloc] initWithFrame:frame];
tempView.backgroundColor = [UIColor blackColor];
tempView.alpha = level;

// Draw the image into a new graphics context
UIGraphicsBeginImageContext(frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[image drawInRect:frame];

// Flip the context vertically so we can draw the dark layer via a mask that
// aligns with the image's alpha pixels (Quartz uses flipped coordinates)
CGContextTranslateCTM(context, 0, frame.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextClipToMask(context, frame, image.CGImage);
[tempView.layer renderInContext:context];

// Produce a new image from this context
CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage *toReturn = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
UIGraphicsEndImageContext();
[tempView release];
return toReturn;
}

关于objective-c - 如何使PNG变暗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9550085/

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