是否可以在不改变UIView边界的情况下缩放UIView内的图像? (即,仍然将图像剪切到UIView的边界,即使图像比UIView更大。)
我在不同的SO帖子上发现了一些代码,用于在UIView中缩放图像:
view.transform = CGAffineTransformScale(CGAffineTransformIdentity, _scale, _scale);
然而,这似乎影响了视图的界限 - 使它们更大 - 因此UIView的绘图现在踩着其他附近的UIViews,因为它的内容变大了。我可以使其内容缩放,同时保持剪裁边界相同吗?
答案 0 :(得分:1)
缩放图像的最简单方法是通过设置其contentMode属性来使用UIImageView。
如果必须使用UIView显示图像,可以尝试在UIView中重绘图像。
1.subclass UIView
2.在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);
}