xamarin - 从图库中获取透明图像时如何设置背景颜色
问题描述
我想在从图库中获取图像时设置图像的背景颜色,因为如果我拍摄透明图像,它会自动在图像后面设置黑色背景。
但是如果我在 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;
});
}
解决方案
你可以看看效果是不是你想要的
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加载图片
推荐阅读
- azure - 当我们进行重定向时,为什么前门会删除授权标头?
- java - Spring 4 Session Cookie 更改字段
- python - 在另一个框架中查找 Dataframe 字段,如果找到则标记它
- javascript - 使用反应js_在下一页上没有路由按钮导航到按钮单击时的全新页面
- php - 获取数据表jquery中两个日期之间的记录
- javascript - VueJS - 将全局变量从数据共享到内部 scss 文件(动态 CSS)
- javascript - TypeError: Falsy value found in plugins - Vue Unit Testing with Jest
- php - php传递函数并将返回值返回给调用函数
- sql - 循环通过存储过程 Postgres 中的 JSON 数据
- nginx - .well-known 文件夹权限被拒绝 nginx