首页 > 解决方案 > 从图库中获取透明图像时如何设置背景颜色

问题描述

我想在从图库中获取图像时设置图像的背景颜色,因为如果我拍摄透明图像,它会自动在图像后面设置黑色背景。

在此处输入图像描述

但是如果我在 Resources-->drawable 文件夹中保留透明图像,那么它会显示给定的红色背景

 <Grid Grid.Column="1" BackgroundColor=">
    <Image x:Name="RestaurantImage" Source="trans.png" BackgroundColor="Red"/>
 </Grid

在此处输入图像描述 这是我的拍摄图像代码:

private async void ImageTapped(object sender, EventArgs e)
{
           string action = await UserDialogs.Instance.ActionSheetAsync("PickPhoto", "Cancel", null, null, "Take Photo", "Pick From Gallery");
           MediaFile file = null;
           if (action == "Take Photo")
           {
               await CrossMedia.Current.Initialize();
               if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
               {
                   UserDialogs.Instance.Alert("No Camera", ":( No camera avaialble.", "OK");
                   return;
               }
               file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
               {
                   PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,
                   Directory = "Sample",
                   Name = "test.png"
               });
           }
           else if (action == "Pick From Gallery")
           {
               if (!CrossMedia.Current.IsPickPhotoSupported)
               {
                   UserDialogs.Instance.Alert("PhotosNotSupported", "PermissionNotGrantedToPhotos.", "OK");
                   return;
               }
               else
               {
                   file = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions
                   {
                       PhotoSize = PhotoSize.Medium
                   });
               }
           }
           else
           {
               return;
           }
           if (file == null)
               return;
            Stream s = file.GetStream();
           RestaurantImage.Source = ImageSource.FromStream(() =>
           {
               file.Dispose();
               return s;
           });
}

标签: xamarinxamarin.forms

解决方案


你可以看看效果是不是你想要的

1.创建一个CustomImage.cs

public class CustomImage:Image
{

}

2.在Droid项目中创建一个CustomImageRenderer :

[assembly: ExportRenderer(typeof(CustomImage), typeof(CustomImageRenderer))]
namespace App18.Droid
{
  class CustomImageRenderer:ImageRenderer
   {
     protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
       {
        base.OnElementChanged(e);
         if (Control != null)
          {
            ImageView image = Control as ImageView;
            image.SetColorFilter(Android.Graphics.Color.Red, Android.Graphics.PorterDuff.Mode.DstOver);
          }

       }
   }
}

最后使用CustomImage加载图片


推荐阅读