2013-10-24 52 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