ios - 在 UIImageView 中移动 UIImage

标签 ios objective-c uiimageview uiimage

我有一个 UIImageView(红色方 block ),它将显示一个必须缩放的 UIImage(我可以接收比 UIImageView)。缩放后,UIImage 的显示部分是它的中心。

我需要的是显示图片中蓝色方 block 的部分,如何存档?

我只能获取图像尺寸(高度和宽度),但它显示原始尺寸,而它应该是缩放后的尺寸。

self.viewIm = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 120, 80)];
self.viewIm.backgroundColor = [UIColor greenColor];
self.viewIm.layer.borderColor = [UIColor redColor].CGColor;
self.viewIm.layer.borderWidth = 5.0;
UIImage *im = [UIImage imageNamed:@"benjen"];
self.viewIm.image = im;
self.viewIm.contentMode = UIViewContentModeScaleAspectFill;
//    self.viewim.clipsToBounds = YES;
[self.view addSubview:self.viewIm];

enter image description here

最佳答案

要完成您想要做的事情,我建议查看 CALayercontentsRect属性(property)。

自从看到您的回答后,我一直在尝试找出正确的解决方案一段时间,但数学让我逃脱了,因为 contentsRect: 的 x 和 y 参数看起来有点神秘...但这里有一些代码可能会为您指明正确的方向......

float imageAspect = self.imageView.image.size.width/self.imageView.image.size.height;
float imageViewAspect = self.imageView.frame.size.width/self.imageView.frame.size.height;

if (imageAspect > imageViewAspect) {
    float scaledImageWidth = self.imageView.frame.size.height * imageAspect;
    float offsetWidth = -((scaledImageWidth-self.imageView.frame.size.width)/2);
    self.imageView.layer.contentsRect = CGRectMake(offsetWidth/self.imageView.frame.size.width, 0.0, 1.0, 1.0);
} else if (imageAspect < imageViewAspect) {
    float scaledImageHeight = self.imageView.frame.size.width * imageAspect;
    float offsetHeight = ((scaledImageHeight-self.imageView.frame.size.height)/2);
    self.imageView.layer.contentsRect = CGRectMake(0.0, offsetHeight/self.imageView.frame.size.height, 1.0, 1.0);
}

关于ios - 在 UIImageView 中移动 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28705697/

相关文章:

ios - 快速访问数组中对象的属性,返回 nil

ios - 应用程序可以为 NSDocumentDirectory 设置多个路径吗

iphone - 当 UIButton 正在动画时,我想识别按钮上的事件

c++ - 在 IOS 上打印漂亮的大数字 C++

ios - 在 iOS 中将图像大小减小至最大 100 kb,并固定尺寸 512x512

来自两个文本字段的 IOS 快速日期选择器

objective-c - 我可以向此代码添加什么以使其不删除 UIToolbar?

ios - iCloud Drive 与 iCloud 文档

iOS:如何让动画播放3次结束?

ios - 在最后一张图像处停止 UIimageview 动画