我找不到任何解决这个问题的方法。这是我的代码。
// Xamarin Android
// Call via Dependency Service
Drawable drawable = TextDrawable.Android.Ui.TextDrawable.TextDrawable.TextDrwableBuilder
.BeginConfig()
.FontSize(70)
.WithBorder(2)
.EndConfig().BuildRound("A", Color.Black);
var img = new ImageView(Application.Context);
img.SetImageDrawable(drawable);
我看了很多答案,找到了一个,但是没有用。
BitmapDrawable bitmapDrawable = (img.Drawable as BitmapDrawable); // this is also null every time
Bitmap bitmap;
if (bitmapDrawable == null)
{
img.BuildDrawingCache();
bitmap = img.DrawingCache; **// Here is Null Every Time**
img.BuildDrawingCache(false);
}
else
{
bitmap = bitmapDrawable.Bitmap;
}
byte[] bitmapData;
using (var stream = new MemoryStream())
{
bitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
当我试着这样做的时候,我得到的是 空档 异常。
我有一个NuGet包,它可以使用文本制作一个Drawable对象,并且它也可以转换为ImageView。我想将该Drawable转换为字节[]来返回Xamarin.Forms PCL项目。
谁能建议我在Xamarin跨平台应用程序中应该使用什么来实现文本到图像。
使用以下代码
Bitmap bitmap = ((BitmapDrawable)img.Drawable).Bitmap as Bitmap;
MemoryStream baos = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, baos);
byte[] imageInByte = baos.ToArray();
drawable
是TextDrawable,继承自 ShapeDrawable
但在这里,你把它当作 BitmapDrawable
所以vaule是空的,你可以创建一个Bitmap对象从 drawable
首先是实例。
Drawable drawable = TextDrawable.TextDrwableBuilder
.BeginConfig()
.FontSize(70)
.WithBorder(2)
.EndConfig().BuildRound("A", Color.Black);
ImageView img = v1.FindViewById<ImageView>(Resource.Id.button1) as ImageView;
img.SetImageDrawable(drawable);
TextDrawable bitmapDrawable = drawable as TextDrawable;
Bitmap bitmap = null;
if (bitmapDrawable.IntrinsicWidth<=0 || bitmapDrawable.IntrinsicHeight <= 0)
{
bitmap = Bitmap.CreateBitmap(1, 1, Bitmap.Config.Argb8888);
}
else
{
bitmap = Bitmap.CreateBitmap(bitmapDrawable.IntrinsicWidth, bitmapDrawable.IntrinsicHeight, Bitmap.Config.Argb8888);
}
Canvas canvas = new Canvas(bitmap);
bitmapDrawable.SetBounds(0, 0, canvas.Width, canvas.Height);
bitmapDrawable.Draw(canvas);
MemoryStream baos = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, baos);
byte[] imageInByte = baos.ToArray();