2013-10-24 66 views
1

是否可以在不改变UIView边界的情况下缩放UIView中的图像? (也就是说,虽然仍裁剪图像到的UIView的边界,即使在图像缩放比UIView的大。)在UIView中缩放图像而不改变边界?

我发现了一个不同,所以后一些代码,扩展在一个UIView图像:

view.transform = CGAffineTransformScale(CGAffineTransformIdentity, _scale, _scale); 

但是,这似乎影响视图的界限 - 使它们变大 - 以便UIView的绘图现在随着其内容变大而重叠在其他附近的UIView上。我可以使其内容缩放较大,同时保持剪辑边界相同吗?

+1

图像除了@静的回答,为什么不干脆把UIImageView的容器视图内? –

+0

昨晚我发现这是要走的路。您可以为父视图设置剪切为YES,然后在子视图上更改变换,它可以工作! –

回答

1

缩放图像最简单的方法是使用UIImageView通过设置其contentMode属性。

如果您必须使用UIView来显示图像,您可以尝试在UIView中重新绘制图像。

1.subclass的UIView

2.draw您在drawRect中

//the followed code draw the origin size of the image 

- (void)drawRect:(CGRect)rect 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    [_yourImage drawAtPoint:CGPointMake(0,0)]; 
} 

//if you want to draw as much as the size of the image, you should calculate the rect that the image draws into 

- (void)drawRect:(CGRect)rect 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    [_yourImage drawInRect:_rectToDraw]; 
} 

- (void)setYourImage:(UIImage *)yourImage 
{ 
    _yourImage = yourImage; 

    CGFloat imageWidth = yourImage.size.width; 
    CGFloat imageHeight = yourImage.size.height; 

    CGFloat scaleW = imageWidth/self.bounds.size.width; 
    CGFloat scaleH = imageHeight/self.bounds.size.height; 

    CGFloat max = scaleW > scaleH ? scaleW : scaleH; 

    _rectToDraw = CGRectMake(0, 0, imageWidth * max, imageHeight * max); 
} 
+0

由于您花时间发布了回复,因此将其标记为答案,但是昨天晚上我发现如果我创建一个UIImageView作为子视图,则可以对其进行设置,然后使用YES为父视图调用setClipsToBounds ,并且子视图被裁剪。很棒! –

+0

是的,使用UIImageView是最简单的方法,我已经在第一行 – Jing

+0

中提到过,只需将UIImageView的contentMode设置为Aspect Fill即可达到效果,无需在超级视图中使用clipToBounds – Jing