gpt4 book ai didi

c# - 将布局保存到位图(Xamarin)

转载 作者:太空狗 更新时间:2023-10-29 13:53:23 27 4
gpt4 key购买 nike

我有布局,需要将它保存到位图

这是代码

public void Save()
{
LinearLayout view = FindViewById<LinearLayout>(Resource.Id.badge);

view.DrawingCacheEnabled = true;
view.BuildDrawingCache();
Bitmap layout = view.GetDrawingCache(true);

}

我将断点设置为 Bitmap layout = view.GetDrawingCache(true);,我发现它的布局为空。

我的错误在哪里,如何将布局保存为位图?

更新

我尝试像这样将 View 保存为位图

public  Bitmap CreateBitmapFromView(View view, bool autoScale = true)
{
var wasDrawingCacheEnabled = view.DrawingCacheEnabled;
view.DrawingCacheEnabled = true;
view.BuildDrawingCache(autoScale);
var bitmap2 = view.GetDrawingCache(autoScale);
view.DrawingCacheEnabled = wasDrawingCacheEnabled;
return bitmap2;

}

一切正常,bitmap2 正在返回。

但我还需要将它保存到 SD

我是这样写的

public  Bitmap CreateBitmapFromView(View view, bool autoScale = true)
{
var wasDrawingCacheEnabled = view.DrawingCacheEnabled;
view.DrawingCacheEnabled = true;
view.BuildDrawingCache(autoScale);
var bitmap2 = view.GetDrawingCache(autoScale);
view.DrawingCacheEnabled = wasDrawingCacheEnabled;
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePath = System.IO.Path.Combine(sdCardPath, "test.png");
var stream = new FileStream(filePath, FileMode.Create);
bitmap2.Compress(Bitmap.CompressFormat.Png, 100, stream);
return bitmap2;

}

并且有这个错误。

Object reference not set to an instance of an object.

最佳答案

把它改成这样:

public Bitmap CreateBitmapFromView(View view, bool autoScale = true)
{
var wasDrawingCacheEnabled = view.DrawingCacheEnabled;
view.DrawingCacheEnabled = true;
view.BuildDrawingCache(autoScale);
var bitmap = view.GetDrawingCache(autoScale);
view.DrawingCacheEnabled = wasDrawingCacheEnabled;
return bitmap;
}

更新

尝试将var bitmap2定义为全局变量

public  Bitmap CreateBitmapFromView(View view, bool autoScale = true)
{
var wasDrawingCacheEnabled = view.DrawingCacheEnabled;
view.DrawingCacheEnabled = true;
view.BuildDrawingCache(autoScale);
view.DrawingCacheEnabled = wasDrawingCacheEnabled;
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePath = System.IO.Path.Combine(sdCardPath, "test.png");
var stream = new FileStream(filePath, FileMode.Create);
bitmap2.Compress(Bitmap.CompressFormat.Png, 100, stream);
return bitmap2;
}

关于c# - 将布局保存到位图(Xamarin),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42887611/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com