I wish to load images from Gallery in my CustomView without altering their aspect ratio, and then I wish to draw on it.
I have a custom view which I added dynamically from MainActivity like this:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data!=null && requestCode==PICK_PHOTO_CODE)
{
Uri photoUri=data.getData();
Glide.with(context).asBitmap().load(photoUri).into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
source_bitmap=resource;
RelativeLayout rL=findViewById(R.id.relative);
CustomView customView=new CustomView(getApplicationContext(),source_bitmap);
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(source_bitmap.getWidth(),source_bitmap.getHeight());
customView.setLayoutParams(params);
rL.addView(customView);
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
}
}
And this is my CustomView class:
public class CustomView extends View {
Context context;
Bitmap source_bitmap;
Bitmap bitmap;
Canvas mCanvas;
public CustomView(Context context, Bitmap sourceBitmap) {
super(context);
this.context=context;
this.source_bitmap=sourceBitmap;
init();
}
public void init()
{
}
@Override
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
super.onSizeChanged(w, h, oldW, oldH);
bitmap=Bitmap.createBitmap(source_bitmap.getWidth(),source_bitmap.getHeight(), Bitmap.Config.ARGB_8888);
mCanvas=new Canvas(bitmap);
mCanvas.drawBitmap(source_bitmap,0,0,null);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mCanvas.drawBitmap(bitmap,0,0,null);
}
}
The problem is that the bitmap of the image selected from the Gallery doesn't get drawn on it, and I can't think where's the problem. Can anyone help?
The problem was in the onDraw method, the canvas that has been passed should be used to draw i.e. canvas and not mCanvas. So,
Instead of
use
Only then we can see the results. In the former case, it sure gets drawn but the canvas associated with the custom view is canvas and not mCanvas. This is my understanding. If you find anything incorrect, do comment.