在Xamarin Forms中获取缓存图像源的原始高度和宽度

时间:2018-09-07 14:53:01

标签: c# image xamarin.forms

除了按照以下方法检查是否成功加载之外,还有其他方法可以访问CachedImage的ImageInformation中的OriginalHeight和OriginalWidth吗?

CachedImage img = new CachedImage() 
{ 
    CacheType = FFImageLoading.Cache.CacheType.Memory 
};
img.Source = GetNextImage();
img.Success += (sender, e) =>
{
    h = e.ImageInformation.OriginalHeight;
    w = e.ImageInformation.OriginalWidth;

    if (Device.Idiom == TargetIdiom.Phone)
    {
        if (h > w)
        {
            img.HeightRequest = 400;
        }
    }
    if (Device.Idiom == TargetIdiom.Tablet)
    {
        if (h > w)
        {
            img.HeightRequest = 800;
        }
     }            
 };

1 个答案:

答案 0 :(得分:5)

使用user-agent库,使用FFImageLoading时您的方法是正确的,但是如果您在Resource文件夹下有图片,则可以使用以下方法/想法:

PLC /标准:

Success

Android:

using Xamarin.Forms;

namespace YourProject.Utils
{
    public interface IImageResource
    {
        Size GetSize(string fileName);
    }
}

iOS:

using Android.Graphics;
using YourProject.Droid.Utils;
using YourProject.Utils;
using System;
using Xamarin.Forms;

[assembly: Dependency(typeof(ImageResource))]
namespace YourProject.Droid.Utils
{
    public class ImageResource : Java.Lang.Object, IImageResource
    {
        public Size GetSize(string fileName)
        {
            var options = new BitmapFactory.Options
            {
                InJustDecodeBounds = true
            };

            fileName = fileName.Replace('-', '_').Replace(".png", "").Replace(".jpg", "");
            var resId = Forms.Context.Resources.GetIdentifier(fileName, "drawable", Forms.Context.PackageName);
            BitmapFactory.DecodeResource(Forms.Context.Resources, resId, options);

            return new Size((double)options.OutWidth, (double)options.OutHeight);
        }
    }
}

与Xamarin.Forms.DependencyService一起使用:

using YourProject.iOS.Utils;
using YourProject.Utils;
using System;
using UIKit;
using Xamarin.Forms;

[assembly: Dependency(typeof(ImageResource))]
namespace YourProject.iOS.Utils
{
    public class ImageResource : IImageResource
    {
        public Size GetSize(string fileName)
        {
            UIImage image = UIImage.FromFile(fileName);
            return new Size((double)image.Size.Width, (double)image.Size.Height);
        }
    }
}

通过XAML的另一个选项:

var imageSize = DependencyService.Get<IImageResource>().GetSize("ic_launcher.png");
System.Diagnostics.Debug.WriteLine(imageSize);

然后,您可以创建一个转换器以设置平板电脑/手机的尺寸,也许可行。

希望这对您有所帮助。