2013-03-05 91 views
0

我有兩個UIImageViews,我想從一個複製圖像到另一個,並調整顏色,但它會導致奇怪的拉伸。UIImage繪圖顏色

這裏是我使用,使拷貝代碼:

_selectedIcon.image = groupView.icon; 
[ViewUtils colorImageView:_selectedIcon withRed:0.843 Green:0.3176 andBlue:0.066667]; 

如果我只用一線它複製圖像細膩,看起來像這樣:

Correct

這是有點大,因爲它看起來突出顯示。但它會複製並正確縮放。然後,當我試圖顏色故,它這樣做:

Wrong

這裏是我使用顏色的圖像代碼:

+(void)colorImageView:(UIImageView*)source withRed:(CGFloat)red Green:(float)green andBlue:(float)blue 
{ 
    // Create a context containing the image. 
    UIGraphicsBeginImageContext(source.bounds.size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    // The mask needs to be upside down for some reason 
    CGContextTranslateCTM(context, 0, source.bounds.size.height); 
    CGContextScaleCTM(context, 1.0, -1.0); 
    CGContextClipToMask(context, source.bounds, [source.image CGImage]); 
    CGContextFillRect(context, source.bounds); 

    [[UIColor colorWithRed:red green:green blue:blue alpha:1.0] set]; 
    UIBezierPath *imagePath = [UIBezierPath bezierPathWithRect:source.bounds]; 
    [imagePath fill]; 
    // Retrieve the new image. 
    source.image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
} 

我縮放圖像的嘗試許多不同的方法在着色代碼中,似乎沒有任何工作。有沒有人有建議?

回答

0

我想通了。圖像被拉伸以適應整個UIImageView,所以我需要調整邊界以便正確縮放。這裏是我使用的代碼:

float ratioX = source.bounds.size.width/source.image.size.width; 
float ratioY = source.bounds.size.height/source.image.size.height; 
float ratio = MIN(ratioX, ratioY); 
CGRect bounds = CGRectMake(0, 0, source.image.size.width * ratio, source.image.size.height * ratio);