iPhone UIView 以编程方式替换图像颜色,就像在 Photoshop 或 Illustrator 中一样

标签 iphone objective-c uiview core-graphics

我有一组图形,我想在我的应用程序中重复使用。它们是透明的按钮和图像。与其拥有数十个硬编码的按钮图像,我更希望拥有一个按钮图像,并能够为其动态分配颜色,例如导航栏及其色调。

是否可以替换/移动 UIView 的色调?

或者: 我知道如果我将透明图像覆盖在另一个 UIView 上,那么我可以更改背景颜色并且两个图像将混合在一起。但是透明区域会呈现出背景的色调。

有没有办法在将两个图像混合在一起的同时保持透明区域透明?我听说有剪贴蒙版,但从未使用过它们。

谢谢!

更新:

这应该有效,但返回 nil 图像,我看到其他人报告了同样的问题。也许这在未来会奏效

-(void)doHueAdjustFilter
{

    //does not work, returns nil image
    CIImage* inputImage = [CIImage imageWithCGImage:[[UIImage imageNamed:@"button.jpg"]CGImage]];

    CIFilter *myFilter;
    NSDictionary *myFilterAttributes;
    myFilter = [CIFilter filterWithName:@"CIHueAdjust"];
    [myFilter setDefaults];

    myFilterAttributes = [myFilter attributes];
    [myFilterAttributes setValue:inputImage forKey:@"inputImage"];
    [myFilterAttributes setValue:[NSNumber numberWithFloat:0.9] forKey:@"inputAngle"];


    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *ciimage = [myFilter outputImage];
    CGImageRef cgimg = [context createCGImage:ciimage fromRect:[ciimage extent]];
    UIImage *uimage = [UIImage imageWithCGImage:cgimg scale:1.0f orientation:UIImageOrientationUp];
    [caduceusImageView setImage:uimage];
    CGImageRelease(cgimg);

}

最佳答案

我对这个代码片段感到非常兴奋。它完全改变了图形或按钮的色调。矢量图形看起来像我在 illustrator 中改变了色调。这节省了大量时间,因为我不再需要放下我的工作,切换到 illustrator 并开始绘制具有不同色调的按钮。 一个按钮适用于所有人!

适用于 iOS5

-(UIImage*)doHueAdjustFilterWithBaseImageName:(NSString*)baseImageName hueAdjust:(CGFloat)hueAdjust
{

    CIImage *inputImage = [[CIImage alloc] initWithImage:[UIImage imageNamed:baseImageName]];
    CIFilter * controlsFilter = [CIFilter filterWithName:@"CIHueAdjust"];
    [controlsFilter setValue:inputImage forKey:kCIInputImageKey];

    [controlsFilter setValue:[NSNumber numberWithFloat:hueAdjust] forKey:@"inputAngle"];

    NSLog(@"%@",controlsFilter.attributes);
    CIImage *displayImage = controlsFilter.outputImage;
    UIImage *finalImage = [UIImage imageWithCIImage:displayImage];

    CIContext *context = [CIContext contextWithOptions:nil];
    if (displayImage == nil || finalImage == nil) {
        // We did not get output image. Let's display the original image itself.
       return  [UIImage imageNamed:baseImageName];
    }else {
        // We got output image. Display it.
        return  [UIImage imageWithCGImage:[context createCGImage:displayImage fromRect:displayImage.extent]];
    }


}

关于iPhone UIView 以编程方式替换图像颜色,就像在 Photoshop 或 Illustrator 中一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9470438/

相关文章:

iphone - 如何在最佳GPS位置调用URL API?

Objective-c : How method using block can returns object

ios - "hide"具有自动布局的 subview 的 UIView

ios - 你如何设置 UINavigationBar 的标题

iphone - 定位 UIViewController 包含子项

iphone - 向 Beta 测试人员公开公开 .ipa 和 .mobileprovision 文件

iphone - uibutton 发件人标签

iphone - 如何在 iPhone 中重新加载 UIPickerView?

c++ - 使用 Objective C 类实例调用 C 函数

ios - 是否可以将 GestureRecognizer 添加到自定义 UIView subview 中的标签