1

我希望在我的 CustomView 中从 Gallery 加载图像而不改变它们的纵横比,然后我希望在它上面画画。

我有一个从 MainActivity 动态添加的自定义视图,如下所示:

 @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) {

                }
            });
        }
    }

这是我的 CustomView 类:

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);
    }
}

问题是从图库中选择的图像的位图没有绘制在上面,我想不出问题出在哪里。任何人都可以帮忙吗?

4

1 回答 1

1

问题出在onDraw 方法中,传递的canvas 应该用于绘制即canvas 而不是mCanvas。所以,

代替

mCanvas.drawBitmap(bitmap,0,0,null);

利用

canvas.drawBitmap(bitmap,0,0,null);

只有这样我们才能看到结果。在前一种情况下,它肯定会被绘制,但与自定义视图关联的画布是画布而不是 mCanvas。这是我的理解。如果您发现任何不正确的地方,请发表评论。

于 2021-01-02T08:53:51.143 回答