假設要做一個「喜歡」的按鈕,
沒有按下去之前愛心是黑色的,按下去之後愛心變成紅色的,
若愛心為單一色系的圖案,
在iOS 7以後,不需要設計師分別出兩種顏色的愛心,
可以使用
(UIImage *)imageWithRenderingMode:(UIImageRenderingMode)renderingMode;
這個方法來用程式實現換色的效果:
ObjC
imageView.image = [[UIImage imageNamed:@"imageName"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; imageView.tintColor = [UIColor blackColor];
將image的rendering mode設定為UIImageRenderingModeAlwaysTemplate後,
設定imageView的tintColor就可以任意改變圖案的顏色,
在愛心要變紅色的地方寫下:
imageView.tintColor = [UIColor redColor];
如此一來只要一張圖就可以任意變換顏色,比出各種顏色的圖省力很多!
同理也可使用在UIButton上
2017/08/06 更新
Swift 3.0
imageView.image = UIImage(named: "image")?.withRenderingMode(.alwaysTemplate) imageView.tintColor = UIColor.color