Issue
I can't found any solution of this issue.
Here is my code:
// 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);
I looked through many answer and I found one but it is not working:
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();
}
When I try this I am getting a null ref exception.
I have a NuGet package that make a Drawable object using text and it is also convert into ImageView. I want to convert that Drawable to byte[] to return to Xamarin.Forms PCL Project.
Can anyone suggest what I should use to achieve text to image in Xamarin Cross Platform Application.
Solution
Use the following code
Bitmap bitmap = ((BitmapDrawable)img.Drawable).Bitmap as Bitmap;
MemoryStream baos = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, baos);
byte[] imageInByte = baos.ToArray();
Update
drawable
is TextDrawable which inherits from ShapeDrawable
, but here you use it as BitmapDrawable
, so the vaule is null , you could create a Bitmap object from drawable
instance first .
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();
Refer https://stackoverflow.com/a/46531354/8187800.
Answered By - ColeX
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.