2011-07-29 110 views
0

我想弄清楚如何做到以下幾點:iphone與圖像sdk按鈕

我有一個按鈕,有一個圖像,而不是默認的外觀。用戶點擊按鈕並選擇一張照片(使用圖像選擇器)。我想將照片的圖像設置爲用戶點擊的照片。

所以,我做到以下幾點:

[self.activeBtn setImage:[info objectForKey:@"UIImagePickerControllerOriginalImage"] forState:UIControlStateNormal]; 

不幸的是,這種縮放圖像到小盒子。什麼是確保圖像被按鈕邊框裁剪而不是縮放的最好方法?

編輯:想要說明我目前在模擬器上。

回答

1

您可以使用此功能來創建一個播種的版本交接按鈕的高度和寬度參數

- (UIImage*)thumbnailOfHeight:(int)height andWidth:(int)width fromImage:(UIImage*)image{ 
    UIImage *thumbnail; 

    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];         

    BOOL isWidthGreaterThanHeight = (image.size.width > image.size.height); 
    float sideFull = (isWidthGreaterThanHeight)? image.size.height : image.size.width; 

    CGRect clippedRect = CGRectMake(0, 0, sideFull, sideFull); 

    UIGraphicsBeginImageContext(CGSizeMake(height, width)); 
    CGContextRef currentContext = UIGraphicsGetCurrentContext(); 

    CGContextClipToRect(currentContext, clippedRect); 

    CGFloat scaleFactor = width/sideFull; 

    if (isWidthGreaterThanHeight) { 
     CGContextTranslateCTM(currentContext, -((image.size.width - sideFull)/2)*scaleFactor, 0); 
    } 
    else { 
     CGContextTranslateCTM(currentContext,0, -((image.size.height - sideFull)/2)*scaleFactor); 
    } 
    CGContextScaleCTM(currentContext, scaleFactor, scaleFactor); 

    [imageView.layer renderInContext:currentContext]; 
    thumbnail = UIGraphicsGetImageFromCurrentImageContext(); 

    UIGraphicsEndImageContext(); 
    [imageView release]; 
    return thumbnail; 
} 
+0

非常感謝您爲此片段!我將不得不看看這個UIGraphicsContext的東西,然後做一些圖像處理的東西。 –

+0

嗯...有沒有我需要爲CALayer做的任何導入? LLVM抱怨'imageView.layer'說這是CALayer的前向聲明。 –

+0

是的QuartzCore框架 –

0

您可以設置類似

[self.activeBtn setBackgroundImage:[info objectForKey:@"UIImagePickerControllerOriginalImage"] forState:UIControlStateNormal]; 
+0

不,我可以設置按鈕的背景圖片最初看起來很好。當我使用上面的調用進行設置時,我只是看到圖像/按鈕應該位於的空白區域。 我在模擬器上的方式! –