Xamarin.Forms带有图标的列表应用程序(仅适用于Android) [英] Xamarin.Forms List App with Icon (Android Only)

查看:73
本文介绍了Xamarin.Forms带有图标的列表应用程序(仅适用于Android)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Xamarin Forms项目,我尝试列出带有图标的已安装应用程序.

I have an Xamarin Forms project and i try to have a list of Installed applications with the icon.

现在我有了标签,但是我没有图像.

For now i have the Label, but i dont get the image.

我使用依赖服务获取应用程序列表. :

I use the Dependency Service to get the list of applications. :

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)
                    };
            }
        }

但是我无法在Xamarin Forms项目中将Android Drawable对象转换为ImageSource.这是我现在尝试的:

But i'm not able to convert the Android Drawable object to an ImageSource in the Xamarin Forms project. Here's what i try for now :

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中显示它.

As you can see, i'm new in xamarin and Android ^^ . I did not find on Google how to pass a Drawable from Android to display it in Xamarin Forms.

如果您能为我指出正确的方向,怎么做.

If you can point me the right direction to leard how it can be done.

坦克

添加输出错误

我在输出窗口中收到此错误:

I get this error in the output window:

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

Here is the problem in gitHub : https://github.com/werddomain/Xamarin-Android-Laucher/tree/master/Forms/AndroidCarLaucher

推荐答案

速度更快&更高的内存效率来创建新的ImageSource,将图标作为其原始Drawable加载,而不是转换为位图,字节数组等.这也可以与回收ListView等单元格一起正常使用./p>

ImageSource实现(存在于.NetStd/Forms库中):

It is faster & more memory efficient to create a new ImageSource that loads the icon as its original Drawable vs. converting to a Bitmap, byte array, etc... Also this works correctly with recycling cells in a ListView, etc...

[TypeConverter(typeof(PackageNameSourceConverter))]
public sealed class PackageNameSource : ImageSource
{
    public static readonly BindableProperty PackageNameProperty = BindableProperty.Create(nameof(PackageName), typeof(string), typeof(PackageNameSource), default(string));

    public static ImageSource FromPackageName(string packageName)
    {
        return new PackageNameSource { PackageName = packageName };
    }

    public string PackageName
    {
        get { return (string)GetValue(PackageNameProperty); }
        set { SetValue(PackageNameProperty, value); }
    }

    public override Task<bool> Cancel()
    {
        return Task.FromResult(false);
    }

    public override string ToString()
    {
        return $"PackageName: {PackageName}";
    }

    public static implicit operator PackageNameSource(string packageName)
    {
        return (PackageNameSource)FromPackageName(packageName);
    }

    public static implicit operator string(PackageNameSource packageNameSource)
    {
        return packageNameSource != null ? packageNameSource.PackageName : null;
    }

    protected override void OnPropertyChanged(string propertyName = null)
    {
        if (propertyName == PackageNameProperty.PropertyName)
            OnSourceChanged();
        base.OnPropertyChanged(propertyName);
    }
}

TypeConverter实现(存在于.NetStd/Forms库中):

[TypeConversion(typeof(PackageNameSource))]
public sealed class PackageNameSourceConverter : TypeConverter
{
    public override object ConvertFromInvariantString(string value)
    {
        if (value != null)
            return PackageNameSource.FromPackageName(value);

        throw new InvalidOperationException(string.Format("Cannot convert \"{0}\" into {1}", value, typeof(PackageNameSource)));
    }
}

IImageSourceHandler,IImageViewHandler实现(存在于Xamarin.Android项目中):

public class PackageNameSourceHandler : IImageSourceHandler, IImageViewHandler
{
    public async Task<Bitmap> LoadImageAsync(ImageSource imagesource, Context context, CancellationToken cancelationToken = default(CancellationToken))
    {
        var packageName = ((PackageNameSource)imagesource).PackageName;
        using (var pm = Application.Context.PackageManager)
        using (var info = pm.GetApplicationInfo(packageName, PackageInfoFlags.MetaData))
        using (var drawable = info.LoadIcon(pm))
        {
            Bitmap bitmap = null;
            await Task.Run(() =>
            {
                bitmap = Bitmap.CreateBitmap(drawable.IntrinsicWidth, drawable.IntrinsicHeight, Bitmap.Config.Argb8888);
                using (var canvas = new Canvas(bitmap))
                {
                    drawable.SetBounds(0, 0, canvas.Width, canvas.Height);
                    drawable.Draw(canvas);
                }
            });
            return bitmap;
        }
    }

    public Task LoadImageAsync(ImageSource imagesource, ImageView imageView, CancellationToken cancellationToken = default(CancellationToken))
    {
        var packageName = ((PackageNameSource)imagesource).PackageName;
        using (var pm = Application.Context.PackageManager)
        {
            var info = pm.GetApplicationInfo(packageName, PackageInfoFlags.MetaData);
            imageView.SetImageDrawable(info.LoadIcon(pm));
        }
        return Task.FromResult(true);
    }
}

注意:在组装级别进行注册:

Note: Register this at the assembly level:

[assembly: ExportImageSourceHandler(typeof(PackageNameSource), typeof(PackageNameSourceHandler))]

现在,您的依赖项服务中将返回至少包含PackageName的Android应用程序列表,类似于IList<Package>

Now in your dependency service return a list of Android applications that includes at least the PackageName, something like an IList<Package>

public class Package
{
    public string Name { get; set; }
    public string PackageName { get; set; }
}

Xaml示例:

现在,您可以使用以下PackageNameSource将该IList<Package>绑定到ListView自定义单元格:

Xaml Example:

Now you can bind that IList<Package> to a ListView custom cell using this PackageNameSource:

<Image WidthRequest="60" HeightRequest="60">
    <Image.Source>
        <local:PackageNameSource PackageName="{Binding PackageName}" />
    </Image.Source>
</Image>

这篇关于Xamarin.Forms带有图标的列表应用程序(仅适用于Android)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆