2017-05-22 55 views
0

我想将图像加载到xamarin中使用通用图像加载程序的变量中。但它总是返回null。我尝试了几种方法,但似乎没有任何工作。这是我的代码。唯一一个在非通用图像加载器中工作的。xamarin通用图像加载程序没有放在视图中

private async void GetImages(CardsAdapter adapter, List<Card> cards) 
     { 
      WebClient client = new WebClient(); 

      foreach (var card in cards) 
      { 
       //var data = await client.DownloadDataTaskAsync(card.imageUrl); 
       //card.image = new BitmapDrawable(BitmapFactory.DecodeByteArray(data, 0, data.Length)); 
       //card.image = ImageService.AsBitmapDrawableAsync(); 
       //ImageLoader imageLoader = ImageLoader.Instance; 
       //Bitmap bm = imageLoader.LoadImageSync(card.imageUrl); 
       var bm = await LoadImage(card); 
       card.image = new BitmapDrawable(bm); 
       adapter.NotifyDataSetChanged(); 
      } 
     } 

     private async Task<Bitmap> LoadImage(Card card) 
     { 
      ImageLoader imageLoader = ImageLoader.Instance; 
      Bitmap bm = imageLoader.LoadImageSync(card.imageUrl); 
      //imageLoader.LoadImage(card.imageUrl, new SimpleImageLoadingListener()); 
      //Bitmap bm = null; 
      //imageLoader.LoadImage(
      // card.imageUrl, 
      // new ImageLoadingListener(
      //  loadingComplete: (imageUri, view, loadedImage) => { 
      //   // Do whatever you want with Bitmap 
      //   bm = loadedImage; 
      //  })); 
      return bm; 
     } 

感谢您的帮助!

问候,

比约恩

回答

0

后你的代码的一些测试,你的代码在我身边跑出android.os.NetworkOnMainThreadException异常或ImageLoader must be init with configuration before using错误。第一个异常并没有使程序停止,而是将其抛入日志中。也许这就是为什么你的Bitmap都是空的原因。

你可以试试这个代码:

public class MainActivity : Activity, IImageLoadingListener 
{ 
    //Your ListView and Adapter 
    protected override void OnCreate(Bundle bundle) 
    { 
     base.OnCreate(bundle); 

     // Set our view from the "main" layout resource 
     SetContentView(Resource.Layout.Main); 

     // Set your ListView and Adapter here 

     ImageLoader imageloader = ImageLoader.Instance; 
     imageloader.Init(ImageLoaderConfiguration.CreateDefault(this)); 

     foreach (var card in cards) 
     {   
      imageloader.LoadImage(card.imageUrl, this); 
     }    
    } 

    public void OnLoadingCancelled(string p0, View p1) 
    { 
    } 

    public void OnLoadingComplete(string p0, View p1, Bitmap p2) 
    { 
     foreach (var card in cards) 
     { 
      if (card.imageUrl == p0) 
      { 
       card.image = p2; 
       adapter.NotifyDataSetChanged(); 
      }    
     } 
    } 

    public void OnLoadingFailed(string p0, View p1, FailReason p2) 
    { 
    } 

    public void OnLoadingStarted(string p0, View p1) 
    { 
    } 
} 

此代码的工作由我,如果仍然不能正常工作,请确保您启用了Internet能力和图像的URL是正确的。

相关问题