【问题标题】:Scale image inside UIView without changing bounds?在 UIView 内缩放图像而不改变边界?
【发布时间】:2013-11-02 13:04:48
【问题描述】:

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

我在不同的 SO 帖子上发现了一些代码,可以缩放 UIView 中的图像:

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

但是,这似乎会影响视图的边界——使它们变大——因此 UIView 的绘图现在会随着其内容变大而压倒其他附近的 UIView。我可以将其内容缩放得更大,同时保持剪裁范围不变吗?

【问题讨论】:

  • 除了@Jing 的回答,为什么不把 UIImageView 放在容器视图中?
  • 我昨晚发现这是要走的路。您可以将父视图的剪辑设置为YES,然后在子视图上更改变换,它可以工作!

标签: ios uiview clipping


【解决方案1】:

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

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

1.子类 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);
}

【讨论】:

  • 将其标记为答案,因为您花时间发布回复,虽然昨晚我发现如果我创建一个 UIImageView 作为子视图,我可以在其上设置转换,然后调用setClipsToBounds 为父视图设置 YES,子视图被剪裁。效果很好!
  • 是的,使用 UIImageView 是最简单的方法,我在第一行提到过
  • 只需将UIImageView的contentMode设置为Aspect Fill即可达到效果,在super view中无需使用clipToBounds
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-17
  • 1970-01-01
  • 2014-06-10
  • 2016-03-24
  • 1970-01-01
  • 2021-04-07
相关资源
最近更新 更多