2011-08-19 57 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]; 
}