我有一个Xamarin Forms项目,想要列出已安装应用程序的列表,并显示图标。
目前我只有标签,但是没有图像。
我使用依赖服务来获取应用程序列表:
public IEnumerable<IAppListServiceApplication> GetApplications()
{
var apps = Android.App.Application.Context.PackageManager.GetInstalledApplications(PackageInfoFlags.MatchAll);
foreach (var app in apps)
{
var label = app.LoadLabel(Android.App.Application.Context.PackageManager);
if (!label.ToLower().StartsWith("com."))
yield return new AppListServiceApplication
{
Label = label,
PackageName = app.PackageName,
AppIcon = GetAppIcon(app)
};
}
}
但是我无法将Android Drawable对象转换为Xamarin Forms项目中的ImageSource。目前我尝试的方法如下:
public ImageSource GetAppIcon(ApplicationInfo app)
{
try
{
var drawable = app.LoadIcon(Android.App.Application.Context.PackageManager);
//return ImageSource.FromStream(() => new MemoryStream(bytes));
Bitmap icon = drawableToBitmap(drawable);
return ImageSource.FromStream(() => MemoryStreamFromBitmap(icon));
}
catch (Exception ex)
{
var message = ex.ToString();
return null;
}
}
MemoryStream MemoryStreamFromBitmap(Bitmap bmp)
{
MemoryStream stream = new MemoryStream();
bmp.Compress(Bitmap.CompressFormat.Png, 0, stream);
return stream;
}
Bitmap drawableToBitmap(Drawable drawable)
{
Bitmap bitmap = null;
if (drawable is BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable)drawable;
if (bitmapDrawable.Bitmap != null)
{
return bitmapDrawable.Bitmap;
}
}
if (drawable is AdaptiveIconDrawable)
{
AdaptiveIconDrawable adaptiveIconDrawable = (AdaptiveIconDrawable)drawable;
if (!(adaptiveIconDrawable.IntrinsicWidth <= 0 || adaptiveIconDrawable.IntrinsicHeight <= 0))
{
bitmap = Bitmap.CreateBitmap(drawable.IntrinsicWidth, drawable.IntrinsicHeight, Bitmap.Config.Argb8888);
Canvas c = new Canvas(bitmap);
drawable.SetBounds(0, 0, c.Width, c.Height);
drawable.Draw(c);
return bitmap;
}
}
if (drawable.IntrinsicWidth <= 0 || drawable.IntrinsicHeight <= 0)
{
bitmap = Bitmap.CreateBitmap(1, 1, Bitmap.Config.Argb8888); // Single color bitmap will be created of 1x1 pixel
}
else
{
bitmap = Bitmap.CreateBitmap(drawable.IntrinsicWidth, drawable.IntrinsicHeight, Bitmap.Config.Argb8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.SetBounds(0, 0, canvas.Width, canvas.Height);
drawable.Draw(canvas);
return bitmap;
}
如您所见,我是一个新手,正在学习Xamarin和Android ^^。 我在Google上没有找到如何将Android中的Drawable传递到Xamarin Forms以显示它的方法。
如果您能指导我正确的方向来了解如何实现它,我将不胜感激。
谢谢
编辑:添加输出错误
我在输出窗口中看到以下错误:
ImageLoaderSourceHandler: Image data was invalid: Xamarin.Forms.StreamImageSource
11-05 04:31:19.287 D/skia (10270): --- SkAndroidCodec::NewFromStream returned null
**编辑:** 添加项目
这是GitHub上的问题: https://github.com/werddomain/Xamarin-Android-Laucher/tree/master/Forms/AndroidCarLaucher