Here's the meat of my ImageGetter, it seems to resize just fine inside the TextView however its always left aligned. There have been some wonderful resources to get me where I am on resizing and also on handling base64. The last hurdle I have seems pretty straight forward, is there a way to center the image inside the TextView?
public Drawable getDrawable(String source) {
Bitmap bitmap;
if(source.matches("data:image.*base64.*")) {
String base_64_source = source.replaceAll("data:image.*base64", "");
byte[] data = Base64.decode(base_64_source, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Drawable image = new BitmapDrawable(context.getResources(), bitmap);
image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
return image;
} else {
URLDrawable urlDrawable = new URLDrawable();
ImageGetterAsyncTask asyncTask = new ImageGetterAsyncTask(urlDrawable);
asyncTask.execute(source);
return urlDrawable; //return reference to URLDrawable where We will change with actual image from the src tag
}
}
public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
URLDrawable urlDrawable;
public ImageGetterAsyncTask(URLDrawable d) {
this.urlDrawable = d;
}
@Override
protected Drawable doInBackground(String... params) {
String source = params[0];
return fetchDrawable(source);
}
@Override
protected void onPostExecute(Drawable result) {
urlDrawable.setBounds(0, 0, width, height);//set the correct bound according to the result from HTTP call
urlDrawable.drawable = result; //change the reference of the current drawable to the result from the HTTP call
URLImageParser.this.container.invalidate(); //redraw the image by invalidating the container
container.setText(container.getText());
}
public Drawable fetchDrawable(String urlString) {
try {
DisplayMetrics metrics;
new DisplayMetrics();
metrics = Resources.getSystem().getDisplayMetrics();
InputStream is = (InputStream) new URL(urlString).getContent();
Bitmap bmp = BitmapFactory.decodeStream(is);
Drawable drawable = new BitmapDrawable (context.getResources(), bmp);
//Need logic here to calculate maximum width of image vs height so it doesnt strech
int originalWidthScaled = (int) (drawable.getIntrinsicWidth() * metrics.density);
int originalHeightScaled = (int) (drawable.getIntrinsicHeight() * metrics.density);
if (originalWidthScaled > (metrics.widthPixels * 70) / 100) {
width = (metrics.widthPixels * 70) / 100;
height = drawable.getIntrinsicHeight() * width
/ drawable.getIntrinsicWidth();
}else {
height = originalHeightScaled;
width = originalWidthScaled;
}
drawable.setBounds(0, 0, width, height);
return drawable;
} catch (Exception e) {
return null;
}
}
}