把长方形的图片截取成正方形

本文介绍了一个用于裁剪UIImage的方法实现。该方法接受一个UIImage对象作为输入参数,并返回一个按指定矩形区域裁剪后的UIImage对象。通过计算目标区域的位置和大小来确保裁剪效果符合预期。

- (UIImage *)imageFromImage:(UIImage *)image {

    CGSize size = image.size;

    CGRect rect = CGRectZero;

    rect.size = size;

    rect.origin.x = (size.width - size.height) / 2;

    rect.size.width -= 2 * rect.origin.x;

    CGImageRef sourceImageRef = [image CGImage];

    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);

    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];

    return newImage;

}


截取图片中间的正方形部分,你可以使用CSS来设置图片的显示方式。具体来说,可以通过设置`object-fit`属性为`cover`,并调整`object-position`属性来控制显示哪一部分的图片。 以下是一个简单的示例: ```html <template> <div class="image-container"> <img class="image-size" :src="imgURL" alt="" @click="showBigImage = true" /> </div> </template> <style scoped> .image-container { width: 300px; /* 容器宽度 */ height: 300px; /* 容器高度 */ overflow: hidden; /* 隐藏溢的部分 */ } .image-size { width: 100%; /* 图片宽度 */ height: 100%; /* 图片高度 */ object-fit: cover; /* 保持图片比例,填充整个容器 */ object-position: center; /* 从图片中心开始显示 */ } </style> ``` 在这个示例中,`.image-container`是一个固定大小的容器,而`.image-size`是图片本身。通过设置`object-fit: cover`和`object-position: center`,可以确保图片以覆盖的方式填满容器,并且从图片的中心部分开始显示。这样,最终显示来的就是一个位于图片中心的正方形部分。 如果你需要动态计算并截取图片的中间部分,可以使用JavaScript来实现。以下是一个更复杂的示例: ```html <template> <div class="image-container"> <img class="image-size" ref="image" :src="imgURL" alt="" @click="showBigImage = true" /> </div> </template> <script> export default { data() { return { imgURL: 'your-image-url.jpg', // 替换为你的图片URL showBigImage: false, }; }, mounted() { this.cropImage(); }, methods: { cropImage() { const img = this.$refs.image; img.onload = () => { const containerWidth = 300; // 容器宽度 const containerHeight = 300; // 容器高度 const aspectRatio = img.naturalWidth / img.naturalHeight; let newWidth, newHeight; if (aspectRatio > 1) { newHeight = containerHeight; newWidth = containerHeight * aspectRatio; } else { newWidth = containerWidth; newHeight = containerWidth / aspectRatio; } const x = (newWidth - containerWidth) / 2; const y = (newHeight - containerHeight) / 2; img.style.width = `${newWidth}px`; img.style.height = `${newHeight}px`; img.style.objectFit = 'none'; img.style.objectPosition = `-${x}px -${y}px`; }; }, }, }; </script> <style scoped> .image-container { width: 300px; /* 容器宽度 */ height: 300px; /* 容器高度 */ overflow: hidden; /* 隐藏溢的部分 */ } .image-size { display: block; /* 确保图片是块级元素 */ } </style> ``` 在这个示例中,我们使用JavaScript来计算图片的新尺寸,并通过设置`object-position`属性来截取图片的中间部分。这样可以确保无论图片的原始尺寸如何,最终显示的都是一个位于图片中心的正方形部分。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值