Showing posts with label bitmap. Show all posts
Showing posts with label bitmap. Show all posts

Saturday, October 13, 2018

Select multiple bitmaps using OnTouchEvent

Leave a Comment

I am developing a card based game, in which user can select one or multiple cards from its deck and replace the cards with cards of other decks. I am using onTouchEvent to detect whether the user has selected any bitmap or not and replace that Bitmap with Bitmap of other deck. However OnTouchEvent only allows me to select one bitmap at a time. How can I select multiple bitmaps from my deck? Also I want to know if there is any better approach to swap bitmaps other than the one I used.

Thread Class:

 class MySurfaceViewThread:BaseThread {     private MySurfaceView mysurfaceview;     private ISurfaceHolder myThreadSurfaceHolder;     bool running;      public MySurfaceViewThread(ISurfaceHolder paramSurfaceHolder, MySurfaceView paramSurfaceView)     {         mysurfaceview = paramSurfaceView;         myThreadSurfaceHolder = paramSurfaceHolder;      }     public override void RunThread()     {          Canvas c;         while (running)         {             c = null;             try             {               c = myThreadSurfaceHolder.LockCanvas(null);                  mysurfaceview.Render(c);            //  mysurfaceview.PostInvalidate();              }             catch (Exception ex)             {                 System.Diagnostics.Debug.WriteLine(ex.ToString());             }             finally             {                 if (c != null)                 {                     myThreadSurfaceHolder.UnlockCanvasAndPost(c);                    }              //   running = false;             }          }      }     public override void SetRunning(bool paramBoolean)     {         running = paramBoolean;     } } 

OnTouchEvent:

 public override bool OnTouchEvent(MotionEvent e)     {         Log.Debug(Tag, "Inside" + System.Reflection.MethodBase.GetCurrentMethod().Name + "Method");         float lasttouched_X, lasttouched_Y;         Cards localcard;         int index=-1;          //switch (e.Action) {          //    case MotionEventActions.Up: Log.Info(Tag, "Up Event is Triggered");         //        break;         //    case MotionEventActions.Move: Log.Info(Tag, "Move Event is Triggered");         //        break;         //    case MotionEventActions.Down: Log.Info(Tag, "Down Event is triggered");          //        break;          //}         MotionEventActions action = e.Action;         if (e.Action == MotionEventActions.Down || e.Action== MotionEventActions.Move)         {             Log.Info(Tag, "Down Event is triggered");             lasttouched_X = e.GetX();             lasttouched_Y = e.GetY();             if (TouchedCard == null)             {                 index = CardTouched((int)lasttouched_X, (int)lasttouched_Y);                 TouchedCard = MainPlayer.getCard(index);                 cardindex = index;             }             else             {                 if (TouchedCard != null && ((lasttouched_X >= DiscardDeck_CurrentX && lasttouched_X < (DiscardDeck_CurrentX + DiscardedDeck.getCard().Image.Width)) && (lasttouched_Y >= DiscardDeck_CurrentY && lasttouched_Y < (DiscardDeck_CurrentY + DiscardedDeck.getCard().Image.Width))))                 {                     ReplacedCard = DiscardedDeck.getCard();                 }                  if (ReplacedCard != null)                     SwapCards(ReplacedCard, MainPlayer, cardindex);             }          }         return true;     }      private void SwapCards(Cards replacedCard, Deck mainPlayer, int index)     {          Cards temp = mainPlayer.getCard(index);         mainPlayer.SetCurrentCard(replacedCard, index);         DiscardedDeck.SetCurrentCard(temp, DiscardedDeck.CardsLeft()-1);         TouchedCard = null;         cardindex = -1;      }      private int CardTouched(int lasttouched_X, int lasttouched_Y)     {         int index = 0;         Cards localcard = null;         while (index < MainPlayer.CardsLeft())         {             localcard = MainPlayer.getCard(index);             if (lasttouched_X >= localcard.current_X && lasttouched_X < (localcard.current_X + localcard.Image.Width) && (lasttouched_Y>=localcard.current_Y && lasttouched_Y<(localcard.current_Y+localcard.Image.Width)))                 return index;             index++;         }          return -1;     } 

0 Answers

Read More

Friday, August 18, 2017

Getting Bitmap from WebView generates OutOfMemory crash

Leave a Comment

I have a custom WebView and I want to get a bitmap of its content (offscreen included). I used this code, which I got from here:

 public static Bitmap getBitmapFromWebviewV2(WebView webView) {     webView.measure(View.MeasureSpec.makeMeasureSpec(         View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),         View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));     webView.layout(0, 0, webView.getMeasuredWidth(),             webView.getMeasuredHeight());     webView.setDrawingCacheEnabled(true);     webView.buildDrawingCache();     Bitmap bm = Bitmap.createBitmap(webView.getMeasuredWidth(),             webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);      Canvas bigcanvas = new Canvas(bm);     Paint paint = new Paint();     int iHeight = bm.getHeight();     bigcanvas.drawBitmap(bm, 0, iHeight, paint);     webView.draw(bigcanvas);     return bm; } 

It works fine up to the point when I zoom in a lot, in which case I get OutOfMemory Crash. I tested this with the same picture (slightly zoomed and zoomed to the max) and it behaves in the same way I mentioned above.

I tried to counter this by adding

while(webView.canZoomOut()){       webView.zoomOut(); } 

at the start, but it doesn't help at all.

3 Answers

Answers 1

Okay, I've cracked this one meself. The problem indeed was in the fact that the function returned the Bitmap waay before the zooming out procedure was over, so I had to delay it.

I incorporated

Handler handler = new Handler();         handler.postDelayed(new Runnable() {             @Override             public void run() {                 //bulk of my code             }         }, 1000); 

which forced to change the structure of the function from public Bitmap to public void. Here's directly related thread. Despite some minor tweaks I still need to fix, the approach works like a charm

Answers 2

Quick fix:-

Set android:largeHeap="true" in your AndroidManifest.xml file.

<application     android:name="yourapplication"     android:allowBackup="true"     android:icon="@mipmap/ic_launcher_rounded"     android:label="@string/app_name"     android:largeHeap="true"     android:roundIcon="@mipmap/ic_launcher_rounded"     android:supportsRtl="true"     android:theme="@style/AppTheme"> 

Gud luck :)

Answers 3

You write code to capture Bitmap from Webview but code which creates outOfmemmory you should write onces.

webView.measure(View.MeasureSpec.makeMeasureSpec(             View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),             View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));  Bitmap bm = Bitmap.createBitmap(webView.getMeasuredWidth(),                 webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888); 

So above code should be written once and create Bitmap object Global and check if it's not null then over right new drawing cache in Bitmap.

Because each time when you create new Bitmap it consumes a lot of memory.

Read More

Sunday, August 6, 2017

InvalidOperationException while saving a bitmap and using graphics.copyFromScreen parallel-y

Leave a Comment

I am writing an application to capture the screen using the CopyFromScreen method, and also want to save the image I capture to send over my local network. So, I am trying store the captured screen on one bitmap, and save another bitmap, which is the previously captured screen, on two threads.

However, this is throwing an InvalidOperationException, which says object is currently in use elsewhere. The exception is thrown by System.Drawing.dll.
I have tried locking, and am using separate bitmaps for saving and capturing the screen. How do I stop this from happening? Relevant code:

Bitmap ScreenCapture(Rectangle rctBounds) {     Bitmap resultImage = new Bitmap(rctBounds.Width, rctBounds.Height);      using (Graphics grImage = Graphics.FromImage(resultImage))     {         try         {             grImage.CopyFromScreen(rctBounds.Location, Point.Empty, rctBounds.Size);         }         catch (System.InvalidOperationException)         {             return null;         }     }     return resultImage; }  void ImageEncode(Bitmap bmpSharedImage) {     // other encoding tasks     pictureBox1.Image = bmpSharedImage;     try     {         Bitmap temp = (Bitmap)bmpSharedImage.Clone();         temp.Save("peace.jpeg");     }     catch (System.InvalidOperationException)     {         return;     } }  private void button1_Click(object sender, EventArgs e) {     timer1.Interval = 30;     timer1.Start(); }  Bitmap newImage = null;  private async void timer1_Tick(object sender, EventArgs e) {     //take new screenshot while encoding the old screenshot       Task tskCaptureTask = Task.Run(() =>         {             newImage = ScreenCapture(_rctDisplayBounds);         });     Task tskEncodeTask = Task.Run(() =>             {                 try                 {                     ImageEncode((Bitmap)_bmpThreadSharedImage.Clone());                 }                 catch (InvalidOperationException err)                 {                     System.Diagnostics.Debug.Write(err.Source);                 }             });      await Task.WhenAll(tskCaptureTask, tskEncodeTask);      _bmpThreadSharedImage = newImage; } 

img1img2

2 Answers

Answers 1

I reproduced your problem in a nutshell by creating a simple winforms project with a single button on it.

public partial class Form1 : Form {     public Form1()     {         InitializeComponent();     }      private void button1_Click(object sender, EventArgs e)     {         Task.Run(() => SomeTask());     }      public void SomeTask() //this will result in 'Invalid operation exception.'     {         var myhandle = System.Drawing.Graphics.FromHwnd(Handle);         myhandle.DrawLine(new Pen(Color.Red), 0, 0, 100, 100);     } } 

In order to fix this you need to do the following:

public partial class Form1 : Form {     private Thread myUIthred;      public Form1()     {         myUIthred = Thread.CurrentThread;         InitializeComponent();     }      private void button1_Click(object sender, EventArgs e)     {         Task.Run(() => SomeTask());     }      public void SomeTask() // Works Great.     {         if (Thread.CurrentThread != myUIthred) //Tell the UI thread to invoke me if its not him who is running me.         {             BeginInvoke(new Action(SomeTask));             return;         }         var myhandle = System.Drawing.Graphics.FromHwnd(Handle);         myhandle.DrawLine(new Pen(Color.Red), 0, 0, 100, 100);     }  } 

The issue is (as Spektre implied) a result of trying to call a UI method from a non-UI thread. The 'BeginInvoke' is actually `this.BeginInvoke' and 'this' is the form which was created by the UI thread and therefore all works.

Answers 2

I do not code in C# so I may be wrong here but I assume you are using Windows...

Accessing any visual components (like GDI Bitmap or window ...) is not safe outside WndProc function. So if you are using GDI bitmap (bitmap with device context) or rendering/accessing any visual component from your window inside any thread then there is your problem. After that any call to WinAPI in your app can throw an exception (even unrelated to graphics)

So try to move any such code into your WndProc function. In case you do not have access to it use any event of your window (like OnTimer or OnIdle).

Read More

Saturday, February 11, 2017

Taking OLE (bitmap) object form MS Access database in Visual studio C# , What's wrong in my code?

Leave a Comment

I am trying to fetch an image from MS Access DB. Data is fetched correctly but when I'm trying to display some error is showing. My code for display the image is,

            ...             byte[] photoBytes = (byte[])res[11];             var ms = new System.IO.MemoryStream(photoBytes);             image.Image = new System.Drawing.Bitmap(ms);             ... 

Error : Additional information: Parameter is not valid. enter image description here

Can anyone tell me where is the error, or probability of error?

my function is

public OleDbDataReader studentInfo(String adm_no)     {         OleDbConnection con = new OleDbConnection(ConnStr);         con.Open();         OleDbCommand command = new OleDbCommand("SELECT * FROM student_info WHERE adm_no = '"+adm_no+"'", con);         OleDbDataReader res = command.ExecuteReader();         return res;     } 

3 Answers

Answers 1

As far as I can remember OLE's are beasts. If you know for sure what the datatype is you have some chances if you check the binary structure of it. OLE is a container so it's IMO never just the pure content.

I don't have the code anymore but I remember fishing in the hexdumps of the OLE's of different types (Excel, Word, Textfiles, Images, ...) and ending up with a success rate of maybe 80%. If that was because of the types we decided to support or my very restricted knowledge on the inner structure of OLE's I can't tell anymore.

My recommendation for debugging would be to make absolutely sure you have the raw bitmap data before dealing with the binary data at all:

My approach was to create a small object (in this case a bitmap), store it in the DB, get the BLOB of it and lookup the known pattern in there. I remember I found some structures - like the byte size of the searches object - by reverse- engineering and a somewhat stable offset towards the start of the data.

If you, however, happen to know - or even better - have the exact structure and implementation of an OLE- object and are able to deal with it, I am absolutely confident you'll manage to also store it and open it as a bitmap.

Good luck!

Answers 2

Take a look here for an example of what you are trying to do, although that example is for a JPEG not a Bitmap. Since you have a byte[], you will need to do something like this for conversion:

using (MemoryStream ms = new MemoryStream(photoBytes)) {   Bitmap img = (Bitmap)Image.FromStream(ms); } 

Answers 3

There's something wrong with your byte stream. Normally I'd say to check whether the MemoryStream's .Position is set to 0 before passing it into the Bitmap constructor - if it's at the end of the stream, it's possible that you're effectively passing an empty stream - but that shouldn't be the case here.

There are a few places in the constructor where an argument exception would get thrown, but InvaildParameter should be related to something being wrong with the byte stream that you're retrieving. See here: https://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/Bitmap.cs,cbbb65af7f6fafdb,references

And here: https://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/Advanced/Gdiplus.cs,4edcade52d698713

You should validate that your byte stream is a suitable format for GDI+ to be able to load as an image - try writing the bytes out to a file for example and opening it in Paint.

Read More

Tuesday, April 19, 2016

How to create a partially-rounded-corners-rectangular drawable with center-crop and without creating new bitmap?

Leave a Comment

Background

I've already seen how to create a drawable that's circular out of a bitmap, and also how to add an outline (AKA stroke) around it, here.

The problem

I can't find out how to do a similar task for rounding only some of the corners of the bitmap, inside the drawable, without creating a new bitmap, and still do it for a center-crop ImageView.

What I've found

This is what I've found, but it does create a new bitmap, and when using it in an imageView with center-crop (source here):

/**  * Create rounded corner bitmap from original bitmap.  *  * @param input                               Original bitmap.  * @param cornerRadius                        Corner radius in pixel.  * @param squareTL,squareTR,squareBL,squareBR where to use square corners instead of rounded ones.  */ public static Bitmap getRoundedCornerBitmap(final Bitmap input, final float cornerRadius, final int w, final int h,                                             final boolean squareTL, final boolean squareTR, final boolean squareBL, final boolean squareBR) {     final Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);     final Canvas canvas = new Canvas(output);     final int color = 0xff424242;     final Rect rect = new Rect(0, 0, w, h);     final RectF rectF = new RectF(rect);     // make sure that our rounded corner is scaled appropriately     Paint paint = new Paint();     paint.setXfermode(null);     paint.setAntiAlias(true);     canvas.drawARGB(0, 0, 0, 0);     paint.setColor(color);     canvas.drawRoundRect(rectF, cornerRadius, cornerRadius, paint);     // draw rectangles over the corners we want to be square     if (squareTL)          canvas.drawRect(0, 0, w / 2, h / 2, paint);     if (squareTR)          canvas.drawRect(w / 2, 0, w, h / 2, paint);     if (squareBL)          canvas.drawRect(0, h / 2, w / 2, h, paint);     if (squareBR)          canvas.drawRect(w / 2, h / 2, w, h, paint);     paint.setXfermode(PORTER_DUFF_XFERMODE_SRC_IN);     canvas.drawBitmap(input, 0, 0, paint);     return output; } 

And, this is what I've found for creating a rounded corners drawable that acts on all corners:

public static class RoundedCornersDrawable extends Drawable {     private final float mCornerRadius;     private final RectF mRect = new RectF();     private final BitmapShader mBitmapShader;     private final Paint mPaint;      public RoundedCornersDrawable(final Bitmap bitmap, final float cornerRadius) {         mCornerRadius = cornerRadius;         mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,                 Shader.TileMode.CLAMP);         mPaint = new Paint();         mPaint.setAntiAlias(false);         mPaint.setShader(mBitmapShader);         mRect.set(0, 0, bitmap.getWidth(), bitmap.getHeight());     }      @Override     protected void onBoundsChange(final Rect bounds) {         super.onBoundsChange(bounds);         mRect.set(0, 0, bounds.width(), bounds.height());     }      @Override     public void draw(final Canvas canvas) {         canvas.drawRoundRect(mRect, mCornerRadius, mCornerRadius, mPaint);     }      @Override     public int getOpacity() {         return PixelFormat.TRANSLUCENT;     }      @Override     public void setAlpha(final int alpha) {         mPaint.setAlpha(alpha);     }      @Override     public void setColorFilter(final ColorFilter cf) {         mPaint.setColorFilter(cf);     } } 

But this solution only works well if the imageView shows the content while maintaining the same aspect ratio as the bitmap, and also has its size pre-determined.

The question

How to create a center-cropped drawable, that shows a bitmap, has rounded corners for specific corners, and also be able to show an outline/stroke around it?

I want to do it without creating a new bitmap or extending ImageView. Only use a drawable that has the bitmap as the input.

4 Answers

Answers 1

The SMART way is to use the PorterDuff blending mode. It's really simple and slick to create any fancy shading, blending, "crop" effect. you can find a lot of good tutorial about PorterDuff. here a good one.

Answers 2

I always use this library to achieve what you are looking for. you can round any corner you want and also add stroke.

https://github.com/vinc3m1/RoundedImageView

You can use it or see it's source codes just for inspiration.

EDIT

there is no need to use Image View and make bitmap or drawable yourself and show it in Image View. Just replace Image View with Rounded Image View and it will handle everything for you without any extra work in code ! here is sample :

<com.makeramen.roundedimageview.RoundedImageView     xmlns:app="http://schemas.android.com/apk/res-auto"     android:id="@+id/imageView1"     android:scaleType="centerCrop"     app:riv_corner_radius="8dp"     app:riv_border_width="2dp"     app:riv_border_color="#333333"     app:riv_oval="false" /> 

In code, just pass any image resource to it or use any Image Loader with it.

RoundedImageView myRoundedImage=(RoundedImageView)findViewById(R.id.imageView1); myRoundedImage.setImageResource(R.drawable.MY_DRAWABLE); // OR ImageLoader.getInstance().displayImage(YOUR_IMAGE_URL, myRoundedImage); 

if you want to just make specific corners rounded try this:

 <com.makeramen.roundedimageview.RoundedImageView     xmlns:app="http://schemas.android.com/apk/res-auto"     android:id="@+id/imageView1"     android:scaleType="centerCrop"     app:riv_corner_radius_top_right="8dp"     app:riv_corner_radius_bottom_right="8dp"     app:riv_border_width="2dp"     app:riv_border_color="#333333"     app:riv_oval="false" /> 

Answers 3

Well, you can create a new .xml drawable named my_background and paste this code below:

<?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"     android:shape="rectangle"     >     <solid android:color="#00000000"/>     <corners         android:bottomLeftRadius="12dp"         android:bottomRightRadius="12dp"         android:topLeftRadius="12dp"         android:topRightRadius="12dp" />     <stroke         android:width="1dp"         android:color="#000000"         /> </shape> 

Then, you set your ImageButton's, ImageView's background to your new drawable, like this:

android:background="@drawable/my_background" android:scaleType="centerCrop" 

or programatically:

myView.setBackground(R.drawable.my_background); 

Hope it helps!

EDIT:

To programmatically create a similar drawable, you can use it:

GradientDrawable shape = new GradientDrawable();     shape.setShape(GradientDrawable.RECTANGLE);     shape.setCornerRadii(new float[] { 8, 8, 8, 8, 0, 0, 0, 0 });     shape.setColor(Color.TRANSPARENT);     shape.setStroke(3, Color.BLACK);     v.setBackgroundDrawable(shape); 

Answers 4

Ok, here's my try. The only gotcha is that "int corners" is meant to be a set of flags. Such as 0b1111 where each 1 represents a corner to be rounded, and 0 is the opposite. The order is TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT.

example usage first, formatted for readability:

((ImageView) findViewById(R.id.imageView)).setImageDrawable(     new RoundedRectDrawable(         getResources(),         bitmap,         (float) .15,         0b1101,         8,         Color.YELLOW     ) ); 

code:

import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.os.SystemClock;  /**  * Created by mliu on 4/15/16.  */ public class RoundedRectDrawable extends BitmapDrawable { private final BitmapShader bitmapShader; private final Paint p; private final RectF rect; private final float borderRadius; private final float outlineBorderRadius; private final int w; private final int h; private final int corners; private final int border; private final int bordercolor;  public RoundedRectDrawable(final Resources resources, final Bitmap bitmap, float borderRadiusSeed, int corners, int borderPX, int borderColor) {     super(resources, bitmap);     bitmapShader = new BitmapShader(getBitmap(),             BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);     final Bitmap b = getBitmap();     p = getPaint();     p.setAntiAlias(true);     p.setShader(bitmapShader);     w = b.getWidth();     h = b.getHeight();     rect = new RectF(0,0,w,h);     borderRadius = borderRadiusSeed * Math.min(w, h);     border = borderPX;     this.corners = corners;     this.bordercolor = borderColor;     outlineBorderRadius = borderRadiusSeed * Math.min(w+border,h+border); }  @Override public void draw(final Canvas canvas) {     if ((corners&0b1111)==0){         if (border>0) {             Paint border = new Paint();             border.setColor(bordercolor);             canvas.drawRect(rect, border);         }         canvas.drawRect(rect.left + border, rect.top + border, rect.width() - border, rect.height() - border, p);     } else {         if (border >0) {             Paint border = new Paint();             border.setColor(bordercolor);             canvas.drawRoundRect(rect, outlineBorderRadius, outlineBorderRadius, border);              if ((corners & 0b1000) == 0) {                 //top left                 canvas.drawRect(rect.left, rect.top, rect.width() / 2, rect.height() / 2, border);             }             if ((corners & 0b0100) == 0) {                 //top right                 canvas.drawRect(rect.width() / 2, rect.top, rect.width(), rect.height() / 2, border);             }             if ((corners & 0b0010) == 0) {                 //bottom left                 canvas.drawRect(rect.left, rect.height() / 2, rect.width() / 2, rect.height(), border);             }             if ((corners & 0b0001) == 0) {                 //bottom right                 canvas.drawRect(rect.width() / 2, rect.height() / 2, rect.width(), rect.height(), border);             }         }         canvas.drawRoundRect(new RectF(rect.left + border, rect.top + border, rect.width() - border, rect.height() - border), borderRadius, borderRadius, p);         if ((corners & 0b1000) == 0) {             //top left             canvas.drawRect(rect.left + border, rect.top + border, rect.width() / 2, rect.height() / 2, p);         }         if ((corners & 0b0100) == 0) {             //top right             canvas.drawRect(rect.width() / 2, rect.top + border, rect.width() - border, rect.height() / 2, p);         }         if ((corners & 0b0010) == 0) {             //bottom left             canvas.drawRect(rect.left + border, rect.height() / 2, rect.width() / 2, rect.height() - border, p);         }         if ((corners & 0b0001) == 0) {             //bottom right             canvas.drawRect(rect.width() / 2, rect.height() / 2, rect.width() - border, rect.height() - border, p);         }     } }  } 

So, this handles the outline first, if needed, then the bitmap. It marks the canvas up with a rounded rect first, then "squares out" each corner you don't want to round. Seems highly inefficient, and probably is, but average case run time before minimal optimizations (corners = 0b0000, 10 canvas.draw calls) takes ~ 200us on a S7. And, that time is SUPER inconsistent based on phone usage. I've gotten as low as 80us and as high as 1.5ms.

NOTES/WARNING: I am BAD at this. This is not optimal. There's probably better answers already here on SO. The subject matter is just a bit uncommon and difficult to search up. I was originally not going to post this, but at time of writing this is still not marked answered, and the library OP did not wish to use due to problems with their Drawable actually use a very similar approach as my terrible solution. So, now I'm less embarrassed to share this. Additionally, though what I posted today was 95% written yesterday, I know I got some of this code from a tutorial or a SO post, but I can't remember who to attribute cause I didn't end up using it in my project. Apologies whoever you are.

Read More