2011-08-19 32 views
0

我是UIView子類,檢索遠程圖像,然後使用drawRect繪製到視圖。這工作正常,但圖像然後基於我爲我的視圖框架設置的偏斜。iOS:UIImage規模填充UIView

我可以將UIViewContentModeScaleAspectFill的contentMode添加到我的UIView,但它似乎並不適用於我繪製的UIImage,它仍然擠壓UIImage,因爲它遵循視圖幀大小。

好像我應該做類似下面的,但只是放大圖像100%我的框架之內,而不是跟隨contentMode設置:

[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)]; 

我需要做一些具體的事情中的drawRect:使我的圖像跟隨contentMode屬性?

回答

2

我認爲最簡單的解決方案是繼承UIImageView而不是UIView並使用該類的contentMode屬性。那麼你不需要調用drawRect,只需將圖像加載到imageView中即可。或者,如果您需要繼承UIView,請將UIImageView添加到您的視圖,安裝彈簧和支柱,設置contentMode並加載圖像。

+0

爲什麼連子類'UIImageView'?只要使用它。 @nic:'contentMode'是你在'drawRect'中應該尊重的屬性,而不是適用於你的屬性。 'UIImageView'已經服從它了。 – Tommy

+0

UIImageView不調用drawRect。因爲我正在做自定義繪圖,所以我需要使用UIView。 –

+0

@Nathanial,我喜歡只添加一個UIImageView作爲我的主視圖子視圖的想法。它非常完美! –

0

你可以使用類似這樣

// If we have a custom background image, then draw it, othwerwise call super and draw the standard nav bar 
- (void)drawRect:(CGRect)rect 
{ 
    if (navigationBarBackgroundImage) 
    [navigationBarBackgroundImage.image drawInRect:rect]; 
    else 
    [super drawRect:rect]; 
} 

// Save the background image and call setNeedsDisplay to force a redraw 
-(void) setBackgroundWith:(UIImage*)backgroundImage 
{ 
    self.navigationBarBackgroundImage = [[[UIImageView alloc] initWithFrame:self.frame] autorelease]; 
    navigationBarBackgroundImage.image = backgroundImage; 
    [self setNeedsDisplay]; 
}