如何從A顏色平滑的過渡到B顏色
同一個視圖,隨著進度或者其他過程的變化,從A顏色過渡到B顏色。
所有的顏色都是是由RGB三原色組成,在iOS開發中,通過RGB值的組合來顯示不同的顏色。一次A-B其實就是RGB值的改變,如何平滑的過渡呢?那就是等比例的改變RGB值!
那么,如何獲取顏色的RGB值呢?
- (NSArray *)getRGBDictionaryByColor:(UIColor *)originColor{ CGFloat r=0,g=0,b=0,a=0; if ([self respondsToSelector:@selector(getRed:green:blue:alpha:)]) { [originColor getRed:&r green:&g blue:&b alpha:&a]; } else { const CGFloat *components = CGColorGetComponents(originColor.CGColor); r = components[0]; g = components[1]; b = components[2]; a = components[3]; } return @[@(r),@(g),@(b)];}
有了上面的方法,下面就可以計算出連個顏色之間的色差
- (NSArray *)transColorBeginColor:(UIColor *)beginColor andEndColor:(UIColor *)endColor { NSArray<NSNumber *> *beginColorArr = [self getRGBDictionaryByColor:beginColor];// NSArray<NSNumber *> *endColorArr = [self getRGBDictionaryByColor:endColor]; NSArray<NSNumber *> *endColorArr = @[@(1.0),@(1.0),@(1.0)]; return @[@([endColorArr[0] doubleValue] - [beginColorArr[0] doubleValue]),@([endColorArr[1] doubleValue] - [beginColorArr[1] doubleValue]),@([endColorArr[2] doubleValue] - [beginColorArr[2] doubleValue])];}
最后通過過渡系數來返回當前的顏色
- (UIColor *)getColorWithColor:(UIColor *)beginColor andCoe:(double)coe andMarginArray:(NSArray<NSNumber *> *)marginArray { NSArray *beginColorArr = [self getRGBDictionaryByColor:beginColor]; double red = [beginColorArr[0] doubleValue] + coe * [marginArray[0] doubleValue]; double green = [beginColorArr[1] doubleValue]+ coe * [marginArray[1] doubleValue]; double blue = [beginColorArr[2] doubleValue] + coe * [marginArray[2] doubleValue]; return RGBNUM(red, green, blue);}
把獲取到的顏色賦值給相應的控件,這樣便完成了一個顏色過渡的效果。
以上所述是小編給大家介紹的iOS開發中如何實現一個平滑的顏色過渡,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答