draw object/image on canvas

前端 未结 2 1293
故里飘歌
故里飘歌 2020-12-02 14:03

Is there another way to draw an object on a canvas in android?

This code inside draw() doesn\'t work:

Bitmap bmp = BitmapFactory.decodeResource(getResour         


        
相关标签:
2条回答
  • 2020-12-02 14:18

    I prefer to do this as it only generates the image once:

    public class CustomView extends View {
    
        private Drawable mCustomImage;
    
        public CustomView(Context context, AttributeSet attrs) {
            super(context, attrs);
            mCustomImage = context.getResources().getDrawable(R.drawable.my_image);
        }
    
        ...
    
        protected void onDraw(Canvas canvas) {
            Rect imageBounds = canvas.getClipBounds();  // Adjust this for where you want it
    
            mCustomImage.setBounds(imageBounds);
            mCustomImage.draw(canvas);
        }
    }
    
    0 讨论(0)
  • 2020-12-02 14:19
    package com.canvas;
    
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.view.View;
    
    public class Keypaint extends View {
        Paint p;
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            p=new Paint();
            Bitmap b=BitmapFactory.decodeResource(getResources(), R.drawable.icon);
            p.setColor(Color.RED);
            canvas.drawBitmap(b, 0, 0, p);
        }
    
        public Keypaint(Context context) {
            super(context);
        }
    }
    
    0 讨论(0)
提交回复
热议问题