1.Unity商店导入插件;
2.编写脚本:
using System.IO;
using UnityEngine;
using UnityEngine.UI;
using NativeGalleryNamespace;
public class ImagePicker : MonoBehaviour
{
public Image targetImage;
public Button selectButton;
public AspectRatioFitter fitter;
private void Start()
{
selectButton.onClick.AddListener(SelectImage);
}
private void SelectImage()
{
NativeGallery.GetImageFromGallery(OnImageSelected, "Select an image", "image/*");
}
private void OnImageSelected(string imagePath)
{
if (imagePath != null)
{
Texture2D texture = new Texture2D(2, 2);
byte[] imageData = File.ReadAllBytes(imagePath);
texture.LoadImage(imageData);
Sprite sprite = Sprite.Create(
texture,
new Rect(0, 0, texture.width, texture.height),
new Vector2(0.5f, 0.5f)
);
targetImage.sprite = sprite;
// 设置宽高比
if (fitter)
{
fitter.aspectRatio = (float)texture.width / texture.height;
fitter.enabled = true;
}
}
}
}
3.创建Image、Button组件,并赋值给脚本;Image添加AspectRatioFitter,设置为Fit in parent;
4.设置安卓打包存储 SDcard;