轉(zhuǎn)載自:iOS中使用blend改變圖片顏色
標(biāo)記下作者,有空去看看他的其他資源文章。
上級(jí)向的十個(gè)iOS面試問題
關(guān)于作者
OneV's Den
上善若水,人淡如菊
王巍 (@onevcat)泳秀,一名來自中國的 iOS / Unity 開發(fā)者。現(xiàn)居日本榄攀,就職于 LINE嗜傅。正在修行,探求創(chuàng)意之源檩赢。
ObjC 中國與 objc.io 合作最新作品《函數(shù)式 Swift》,《Core Data》,《Swift 進(jìn)階》及《集合類型優(yōu)化》已經(jīng)發(fā)布吕嘀,泊學(xué)網(wǎng)正在開展訂閱贈(zèng)書活動(dòng),也歡迎前往了解
最近對(duì)Core Animation
和Core Graphics
的內(nèi)容東西比較感興趣贞瞒,自己之前也在這塊相對(duì)薄弱偶房,趁此機(jī)會(huì)也想補(bǔ)習(xí)一下這塊的內(nèi)容,所以之后幾篇可能都會(huì)是對(duì)CA和CG學(xué)習(xí)的記錄的文章军浆。
在應(yīng)用里一個(gè)很常見的需求是主題變換:同樣的圖標(biāo)棕洋,同樣的素材,但是需要按照用戶喜愛變?yōu)椴煌念伾谷凇T趇OS5和6的SDK里部分標(biāo)準(zhǔn)控件引入了tintColor
掰盘,來滿足個(gè)性化界面的需求,但是Apple在這方面還遠(yuǎn)遠(yuǎn)做的不夠赞季。一是現(xiàn)在用默認(rèn)控件根本難以做出界面優(yōu)秀的應(yīng)用愧捕,二是tintColor
所覆蓋的并不夠全面,在很多情況下開發(fā)者都無法使用其來完成個(gè)性化定義申钩。解決辦法是什么次绘?最簡(jiǎn)單當(dāng)然是拜托設(shè)計(jì)師大大出圖,想要藍(lán)色主題撒遣?那好邮偎,開PS蓋個(gè)藍(lán)色圖層出一套藍(lán)色的UI;又想加粉色UI义黎,那好禾进,再出一套粉色的圖然后導(dǎo)入Xcode。代碼上的話根據(jù)顏色需求使用image-blue或者image-pink這樣的名字來加載圖片轩缤。
如果有一丁點(diǎn)重構(gòu)的意識(shí)命迈,就會(huì)知道這不是一個(gè)很好的解決方案。工程中存在大量的冗余和重復(fù)(就算你要狡辯這些圖片顏色不同不算重復(fù)火的,你也會(huì)在內(nèi)心里知道這種狡辯是多么無力)壶愤,這是非常致命的。想象一下如果你有10套主題界面馏鹤,先不論應(yīng)用的體積會(huì)膨脹到多少征椒,光是想做一點(diǎn)修改就會(huì)痛苦萬分,比如希望改一下某個(gè)按鈕的形狀湃累,很好勃救,設(shè)計(jì)師大大請(qǐng)重復(fù)地修改10遍,并出10套UI治力,然后一系列的重命名蒙秒,文件移動(dòng)和導(dǎo)入…一場(chǎng)災(zāi)難。
當(dāng)然有其他辦法宵统,因?yàn)檎f白了就是tint不同的顏色到圖片上而已晕讲,如果我們能實(shí)現(xiàn)改變UIImage的顏色,那我們就只需要一套UI马澈,然后用代碼來改變UI的顏色就可以了瓢省,生活有木有一下光明起來呀。嗯痊班,讓我們先從一張圖片開始吧~下面是一張帶有alpha通道的圖片勤婚,原始顏色是純的灰色(當(dāng)然什么顏色都可以,只不過我這個(gè)人現(xiàn)在暫時(shí)比較喜歡灰色而已)涤伐。
我們將用blending給這張圖片加上另一個(gè)純色作為tint馒胆,并保持原來的alpha通道。用Core Graphics來做的話凝果,大概的想法很直接:
- 創(chuàng)建一個(gè)上下文用以畫新的圖片
- 將新的tintColor設(shè)置為填充顏色
- 將原圖片畫在創(chuàng)建的上下文中国章,并用新的填充色著色(注意保持alpha通道)
- 從當(dāng)前上下文中取得圖片并返回
最麻煩的部分可能就是保持alpha通道了。UIImage的文檔中提供了使用blend繪圖的方法drawInRect:blendMode:alpha:
豆村,rect
和alpha
都沒什么問題液兽,但是blendMode
是個(gè)啥玩意兒啊…繼續(xù)看文檔,關(guān)于CGBlendMode
的文檔掌动,里面有一大堆看不懂的枚舉值四啰,比如這樣:
kCGBlendModeDestinationOver
R = S*(1 - Da) + D
Available in iOS 2.0 and later.
Declared in CGContext.h.
完全不懂..直接看之后的Discussion部分:
The blend mode constants introduced in OS X v10.5 represent the Porter-Duff blend modes. The symbols in the equations for these blend modes are:
R is the premultiplied result
S is the source color, and includes alpha
D is the destination color, and includes alpha
Ra, Sa, and Da are the alpha components of R, S, and D
原來如此,R表示結(jié)果粗恢,S表示包含alpha的原色柑晒,D表示包含alpha的目標(biāo)色,Ra眷射,Sa和Da分別是三個(gè)的alpha匙赞。明白了這些以后佛掖,就可以開始尋找我們所需要的blend模式了。相信你可以和我一樣涌庭,很快找到這個(gè)模式:
kCGBlendModeDestinationIn
R = D*Sa
Available in iOS 2.0 and later.
Declared in CGContext.h.
結(jié)果 = 目標(biāo)色和原色透明度的加成芥被,看起來正式所需要的。啦啦啦坐榆,還等什么呢拴魄,開始動(dòng)手實(shí)現(xiàn)看看對(duì)不對(duì)吧~
為了以后使用方便,當(dāng)然是祭出Category席镀,先創(chuàng)建一個(gè)UIImage的類別:
// UIImage+Tint.h
#import <UIKit/UIKit.h>
@interface UIImage (Tint)
- (UIImage *) imageWithTintColor:(UIColor *)tintColor;
@end
暫時(shí)先這樣匹中,當(dāng)然我們也可以創(chuàng)建一個(gè)類方法直接完成從bundle讀取圖片然后加tintColor,但是很多時(shí)候并不如上面一個(gè)實(shí)例方法方便(比如想要從非bundle的地方獲取圖片)豪诲,這個(gè)問題之后再說顶捷。那么就按照之前設(shè)想的步驟來實(shí)現(xiàn)吧:
// UIImage+Tint.m
#import "UIImage+Tint.h"
@implementation UIImage (Tint)
- (UIImage *) imageWithTintColor:(UIColor *)tintColor
{
//We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the device’s main screen.
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
[tintColor setFill];
CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
UIRectFill(bounds);
//Draw the tinted image in context
[self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return tintedImage;
}
@end
簡(jiǎn)單明了,沒有任何難點(diǎn)屎篱。測(cè)試之:[[UIImage imageNamed:@"image"] imageWithTintColor:[UIColor orangeColor]];
焊切,得到的結(jié)果為:
嗯…怎么說呢,雖然tintColor的顏色是變了芳室,但是總覺得怪怪的专肪。仔細(xì)對(duì)比一下就會(huì)發(fā)現(xiàn),原來灰色圖里星星和周圍的灰度漸變到了橙色的圖里好像都消失了:星星整個(gè)變成了橙色堪侯,周圍的一圈漂亮的光暈也沒有了嚎尤,這是神馬情況啊…這種圖能交差的話那算見鬼了,會(huì)被設(shè)計(jì)和產(chǎn)品打死的吧伍宦。對(duì)于無漸變的純色圖的圖來說直接用上面的方法是沒問題的芽死,但是現(xiàn)在除了Metro的大色塊以外哪里無灰度漸變的設(shè)計(jì)啊…檢查一下使用的blend,R = D * Sa
次洼,恍然大悟关贵,我們雖然保留了原色的透明度,但是卻把它的所有的灰度信息弄丟了卖毁。怎么辦揖曾?繼續(xù)刨CGBlendMode
的文檔吧,那么多blend模式應(yīng)該總有我們需要的亥啦。功夫不負(fù)有心人炭剪,kCGBlendModeOverlay
一副嗷嗷待選的樣子:
kCGBlendModeOverlay
Either multiplies or screens the source image samples with the background image samples, depending on the background color. The result is to overlay the existing image samples while preserving the highlights and shadows of the background. The background color mixes with the source image to reflect the lightness or darkness of the background.
Available in iOS 2.0 and later.
Declared in CGContext.h.
kCGBlendModeOverlay可以保持背景色的明暗,也就是灰度信息翔脱,聽起來正是我們需要的奴拦。加入到聲明中,并且添加相應(yīng)的實(shí)現(xiàn)( 順便重構(gòu)一下原來的代碼 :) ):
// UIImage+Tint.h
#import <UIKit/UIKit.h>
@interface UIImage (Tint)
- (UIImage *) imageWithTintColor:(UIColor *)tintColor;
- (UIImage *) imageWithGradientTintColor:(UIColor *)tintColor;
@end
// UIImage+Tint.m
#import "UIImage+Tint.h"
@implementation UIImage (Tint)
- (UIImage *) imageWithTintColor:(UIColor *)tintColor
{
return [self imageWithTintColor:tintColor blendMode:kCGBlendModeDestinationIn];
}
- (UIImage *) imageWithGradientTintColor:(UIColor *)tintColor
{
return [self imageWithTintColor:tintColor blendMode:kCGBlendModeOverlay];
}
- (UIImage *) imageWithTintColor:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode
{
//We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the device’s main screen.
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
[tintColor setFill];
CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
UIRectFill(bounds);
//Draw the tinted image in context
[self drawInRect:bounds blendMode:blendMode alpha:1.0f];
UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return tintedImage;
}
@end
完成届吁,測(cè)試之…好吧错妖,好尷尬绿鸣,雖然顏色和周圍的光這次對(duì)了,但是透明度又沒了啊魂淡..一點(diǎn)不奇怪啊暂氯,因?yàn)?code>kCGBlendModeOverlay本來就沒承諾給你保留原圖的透明度的說潮模。
那么..既然我們用kCGBlendModeOverlay
能保留灰度信息,用kCGBlendModeDestinationIn
能保留透明度信息株旷,那就兩個(gè)blendMode都用不就完事兒了么~嘗試之再登,如果在blend繪圖時(shí)不是kCGBlendModeDestinationIn
模式的話尔邓,則再用kCGBlendModeDestinationIn
畫一次:
// UIImage+Tint.m
#import "UIImage+Tint.h"
@implementation UIImage (Tint)
- (UIImage *) imageWithTintColor:(UIColor *)tintColor
{
return [self imageWithTintColor:tintColor blendMode:kCGBlendModeDestinationIn];
}
- (UIImage *) imageWithGradientTintColor:(UIColor *)tintColor
{
return [self imageWithTintColor:tintColor blendMode:kCGBlendModeOverlay];
}
- (UIImage *) imageWithTintColor:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode
{
//We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the device’s main screen.
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
[tintColor setFill];
CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
UIRectFill(bounds);
//Draw the tinted image in context
[self drawInRect:bounds blendMode:blendMode alpha:1.0f];
if (blendMode != kCGBlendModeDestinationIn) {
[self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
}
UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return tintedImage;
}
@end
結(jié)果如下:
已經(jīng)很完美了晾剖,這樣的話只要在代碼里設(shè)定一下顏色,我們就能夠很輕易地使用同樣一套UI梯嗽,將其blend為需要的顏色齿尽,來實(shí)現(xiàn)素材的重用了。唯一需要注意的是灯节,因?yàn)槊看问褂?code>UIImage+Tint的方法繪圖時(shí)循头,都使用了CG的繪制方法,這就意味著每次調(diào)用都會(huì)是用到CPU的Offscreen drawing炎疆,大量使用的話可能導(dǎo)致性能的問題(主要對(duì)于iPhone 3GS或之前的設(shè)備卡骂,可能同時(shí)處理大量這樣的繪制調(diào)用的能力會(huì)有不足)。關(guān)于CA和CG的性能的問題形入,打算在之后用一篇文章來介紹一下全跨。對(duì)于這里的UIImage+Tint
的實(shí)現(xiàn),可以寫一套緩存的機(jī)制亿遂,來確保大量重復(fù)的元素只在load的時(shí)候blend一次浓若,之后將其緩存在內(nèi)存中以快速讀取。當(dāng)然這是一個(gè)權(quán)衡的問題蛇数,在時(shí)間和空間中做出正確的平衡和選擇挪钓,也正是程序設(shè)計(jì)的樂趣所在。
這篇文章中作為示例的工程和UIImage+Tint可以在Github上找到耳舅,您可以隨意玩弄..我相信也會(huì)是個(gè)來研究每種blend的特性的好機(jī)會(huì)~