ios - 在不改变边界的情况下在 UIView 中缩放图像?

标签 ios uiview clipping

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

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

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

但是,这似乎会影响 View 的边界——使它们变大——因此当 UIView 的内容变大时,它的绘图现在会覆盖其他附近的 UIView。我可以扩大其内容的比例,同时保持裁剪范围不变吗?

最佳答案

缩放图像最简单的方法是通过设置其 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);
}

关于ios - 在不改变边界的情况下在 UIView 中缩放图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19555506/

相关文章:

objective-c - CGContextClipToMask 返回空白图像

css - 如何使用 CSS 计算正确的变换以在特定 Angular 创建切掉 div 上的 Angular

ios - 我应该在哪里声明静态实例?

ios - 更改自动布局常量不会更新其框架

ios - 在主视图 Swift 中嵌入 subview

c++ - 2d 游戏引擎裁剪算法

ios - 旋转后如何调整UICollectionView contentOffset?

iphone - Facebook Feed 对话框不断请求许可

ios - UIbutton在点击后改变颜色

swift - 在 Swift 中循环遍历嵌套堆栈