它需要屏幕截图,但不会在图库中显示。屏幕截图保存到android / data / com.company.name / file.name但我想用文件名截图将其直接保存到图库
到目前为止,我的代码是:
public void Capture()
{
string filename = System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss");
Application.CaptureScreenshot(filename + ".jpg");
Debug.Log("captured screenshot");
}
答案 0 :(得分:5)
查找提供的答案here(第二个)。它运作得很好。
这是最终的代码:
import UIKit
class CustomImageView: UIImageView {
override public func layoutSubviews() {
super.layoutSubviews()
self.roundUpCorners([.topLeft, .bottomLeft], radius: 8)
}
}
extension UIView {
func roundUpCorners(_ corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
你只需致电:
protected const string MEDIA_STORE_IMAGE_MEDIA = "android.provider.MediaStore$Images$Media";
protected static AndroidJavaObject m_Activity;
protected static string SaveImageToGallery(Texture2D a_Texture, string a_Title, string a_Description)
{
using (AndroidJavaClass mediaClass = new AndroidJavaClass(MEDIA_STORE_IMAGE_MEDIA))
{
using (AndroidJavaObject contentResolver = Activity.Call<AndroidJavaObject>("getContentResolver"))
{
AndroidJavaObject image = Texture2DToAndroidBitmap(a_Texture);
return mediaClass.CallStatic<string>("insertImage", contentResolver, image, a_Title, a_Description);
}
}
}
protected static AndroidJavaObject Texture2DToAndroidBitmap(Texture2D a_Texture)
{
byte[] encodedTexture = a_Texture.EncodeToPNG();
using (AndroidJavaClass bitmapFactory = new AndroidJavaClass("android.graphics.BitmapFactory"))
{
return bitmapFactory.CallStatic<AndroidJavaObject>("decodeByteArray", encodedTexture, 0, encodedTexture.Length);
}
}
protected static AndroidJavaObject Activity
{
get
{
if (m_Activity == null)
{
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
m_Activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
}
return m_Activity;
}
}
修改强> 既然你似乎对Unity很陌生,我建议先学习它。无论如何,这里是你如何调用上面提供的代码:
string path = SaveImageToGallery(picture, "Test Picture", "This is a description.");
只需将这两种方法添加到您的代码中,然后从另一个脚本,Unity按钮或其他任何内容调用public void CaptureScreenshot()
{
StartCoroutine(CaptureScreenshotCoroutine(Screen.width, Screen.height));
}
private IEnumerator CaptureScreenshotCoroutine(int width, int height)
{
yield return new WaitForEndOfFrame();
Texture2D tex = new Texture2D(width, height);
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex.Apply();
yield return tex;
string path = SaveImageToGallery(tex, "Name", "Description");
Debug.Log("Picture has been saved at:\n" + path);
}
......
希望这有帮助,