图片未出现在自定义视图渲染器中

时间:2018-10-07 09:40:36

标签: xamarin xamarin.forms xamarin.android

我在共享项目中有这个cusom视图:

public class CustomAdView : View
{

}

然后将其添加到主页中:

var adView = new CustomAdView();
Grid.SetRowSpan(adView, 4);
_mainGrid.Children.Add(adView);
// here if I add an Image instead, it shows without problem.

然后在android项目中,我为CustomAdView创建了一个自定义渲染器,如下所示:

[assembly: ExportRenderer(typeof(CustomAdView), typeof(CustomAdViewRenderer))]
namespace MyApp.Droid.Renderers
{
    public class CustomAdViewRenderer : ViewRenderer<CustomAdView, Android.Views.View>
    {
        public CustomAdViewRenderer(Context context)
            : base(context)
        {

        }

        protected override void OnElementChanged(ElementChangedEventArgs<CustomAdView> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null && Control == null)
                SetNativeControl(CreateAdView());
        }

        // ...

        private Android.Views.View CreateAdView()
        {
            try
            {
                var url = RequestImageUrlFromServer();

                var imageView = new ImageView(Context);
                imageView.Click += (o, e) =>
                {
                    Device.OpenUri(new Uri("http://www.google.com"));
                };
                imageView.SetImageURI(Android.Net.Uri.Parse(url));
                imageView.LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.FillParent, LayoutParams.FillParent);

                return imageView;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}

CreateAdView()正确返回imageView。如果我单击屏幕,它将响应单击事件并打开浏览器,但问题是它不显示图像!

我想我错误地设置了ImageView来源。图片网址是这样的:

https://addeals.s3.amazonaws.com/campaigns/pub8/testing/768x1024_hangman_test.jpg

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以参考以下代码

var iamgeview = new ImageView(Context);
URL url = new URL("xxx");
Bitmap pngBP = BitmapFactory.DecodeStream(url.OpenStream());
iamgeview.SetImageBitmap(pngBP);