UIImage 方面填充偏移

UIImage aspect fill offset

有没有办法为具有纵横比填充的 UIImage 定义自定义偏移量?

因此,当前纵横比填充会缩放图像并将其居中。

但我需要一种方法来定义偏移量,这样我就可以手动调整图像以使其更适合。

这可能吗?我查看了 UIImage class 但我找不到任何东西。

我看不到单独使用 UIImageView 执行此操作的方法,但是如果您将它放在包含视图中,将其设置为纵横比填充,然后更改包含视图的边界,您可以获得所需的影响。这是我的做法:

UIView *containingView = [[UIView alloc] initWithFrame:CGRectInset(self.view.bounds, 10, 10)];
containingView.clipsToBounds = YES;
[self.view addSubview:containingView];

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image"]];
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.frame = containingView.bounds;
imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[containingView addSubview:imageView];

// Offset the image 100 pixels to the left
containingView.bounds = CGRectMake(100.0f, 0.0f, CGRectGetWidth(containingView.bounds), CGRectGetHeight(containingView.bounds));

确保您的 imageView 将 clipsToBounds 设置为 NO(默认值),以便您可以更改 containingView.bounds 以平移图像的某些部分,否则这些部分将被裁剪掉。

SWIFT 4+

let containerView = UIView(frame: view.bounds)
containerView.clipsToBounds = true
view.addSubview(containerView)

let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFill
imageView.frame = containerView.bounds
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
containerView.addSubview(imageView)

containerView.bounds = CGRect(x: imageXOffset,
                              y: imageYOffset,
                              width: containerView.bounds.width,
                              height: containerView.bounds.height)