Reputation: 373
I am trying to draw a bitmap to my SurfaceView
actually with the following code: (this will be run in another Thread
and in a while
, because it needs to refresh the SurfaceView
).
while (true)
{
try
{
// Enable drawing
// ERROR LINE!
Canvas ca = mPreview2.Holder.LockCanvas();
// Get current frame
Bitmap test = mediaPlayer.CurrentFrame;
// Actual drawing
Paint paint = new Paint();
ca.DrawBitmap(test, 0, 0, paint);
// Stop drawing
mPreview2.Holder.UnlockCanvasAndPost(ca);
} catch (Exception ex)
{
throw ex;
}
}
But I've got the following error: (this is happening on line: Canvas ca = mPreview2.Holder.LockCanvas();
Java.Lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.isRecycled()' on a null object reference
Upvotes: 4
Views: 10141
Reputation: 373
Right now I can draw a bitmap, but I have still one problem!
Because the quality of the right screen is really bad (see image):
PROBLEM SOLVED:
What I did is using a MemoryStream
which compress the Bitmap
to .JPG with a quality of 100 and decode the byte
array
to a Bitmap
. It works great now! See code below:
private void DrawCanvas()
{
while (true)
{
Canvas canvas = holder2.LockCanvas();
if (canvas != null)
{
Bitmap currentBitmap = mediaPlayer.CurrentFrame;
if(currentBitmap != null)
{
Paint paint = new Paint();
MemoryStream ms = new MemoryStream();
currentBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, ms);
byte[] bitmapData = ms.ToArray();
Bitmap bitmap = BitmapFactory.DecodeByteArray(bitmapData, 0, bitmapData.Length);
Bitmap scaledBitmap = Bitmap.CreateScaledBitmap(bitmap, mPreview2.Width, mPreview2.Height, true);
canvas.DrawBitmap(scaledBitmap, 0, 0, paint);
bitmap.Recycle();
scaledBitmap.Recycle();
currentBitmap.Recycle();
}
holder2.UnlockCanvasAndPost(canvas);
}
}
}
Upvotes: 5