简体   繁体   English

Swift-从图库和相机中强制拍摄方形照片

[英]Swift - force square photo from library and camera

I'm building an app and I need to FORCE the user to upload square pictures (just like Instagram does), however I'd like to avoid programming an interface from scratch as we're short in time. 我正在构建一个应用程序,我需要强制用户上传方形图片(就像Instagram一样),但是由于我们时间短,我希望避免从头开始编写界面。

It is important to note that the USER must CHOOSE which part of the image he/she wants to show, so cropping the image programatically without asking the user is out of the question. 重要的是要注意,用户必须选择他/她想要显示的图像的哪一部分,因此以编程方式裁剪图像而不询问用户是不可能的。

I've managed to get this to work via camera, however via library I can't seem to force the user to use a square image. 我设法通过相机使它起作用,但是通过图库,我似乎无法强迫用户使用方形图像。 Here's the code I have: 这是我的代码:

func presentGallery(){
    // from library
    picker.allowsEditing = true
    picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    presentViewController(picker, animated: true, completion: nil)
}

Then on my imagepickercontroller: 然后在我的imagepickercontroller上:

    var chosenImage = info[UIImagePickerControllerEditedImage] as! UIImage 

However I don't get the desired result. 但是我没有得到想要的结果。 It would be fine if the "minimum zoom" was to show 100% of the height of the image, or if I could add a white/black background to the top and bottom of the image. 如果“最小缩放”是要显示图像高度的100%,或者我可以在图像的顶部和底部添加白色/黑色背景,那将是很好的。

Here's the problem: 这是问题所在: 在此处输入图片说明

Instead of something like this: 代替这样的事情:

在此处输入图片说明

My app needs to work starting from iOS7. 我的应用需要从iOS7开始运行。

You should do some sort of check to make sure that the picture is square if they're picking from their library. 如果他们从自己的照片库中选取图片,则应进行某种检查以确保图片是正方形的。

Once you get the image (using imagePickerController didFinishPickingMediaWithInfo ), then get the image with [info objectForKey:UIImagePickerControllerOriginalImage]; 一旦获得图像(使用imagePickerController didFinishPickingMediaWithInfo ),然后使用[info objectForKey:UIImagePickerControllerOriginalImage];获得图像[info objectForKey:UIImagePickerControllerOriginalImage]; . Once you've done this, perform the check: 完成此操作后,执行检查:

if (image.size.height != image.size.width) // Show some alert

What might be an even better solution is creating a view which allows the user to pick any photo, and then choose a square part of the photo to import into your app, like Instagram does. 也许更好的解决方案是创建一个视图,该视图允许用户选择任何照片,然后选择照片的正方形部分以导入到您的应用中,就像Instagram一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM