Drawing Canvas on an ImageView / Bitmap

I've been trying to draw a Canvas on an ImageView but after creating a bitmap I see no Image on my screen. The only thing I get is the small circle I've drawn in the onDraw Method. I want to have the Canvas on the ImageView.

I've got the following code:

public class MainActivity extends AppCompatActivity {

  ImageView imageView;
  Bitmap myBitmap;
  Paint paint;
  Button button;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);

  }

  public void onClickButton(View view) {

    View v = new DrawCanvas(getApplicationContext());
    Bitmap bitmap = Bitmap.createBitmap(48, 48, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);

    v.draw(canvas);
    imageView = (ImageView) findViewById(R.id.testpicture);
    imageView.setImageBitmap(bitmap);
  }
}

and

public class DrawCanvas extends View {

    Paint paint = new Paint();

    public DrawCanvas(Context context) {
      super(context);
    }

    public DrawCanvas(Context context, AttributeSet attrs) {
      super(context, attrs);
    }


    @Override
    public void onDraw(Canvas canvas) {
      super.onDraw(canvas);
      paint.setColor(Color.RED);

      canvas.drawCircle(25, 25, 5, paint);
    }
}

Thanks in advance!

Answers


First, you're overcomplicating things. You don't need, or want, a view to do what you're doing. If you want to draw a circle, do it directly to the canvas by using canvas.drawCircle in your onClick.

Second, alling setImageBitmap overwrites any previous bitmap you set. If you want this to show over the previous image, you have 2 options:

1)Use two image views on top of one another, and set the top image to the bitmap made on the canvas (to make this work you may need to make sure the background color on the bitmap is transparent).

2)Create a new view subclassed off ImageView that displays 2 bitmaps by overriding onDraw.

The first approach is probably easier.


Need Your Help

Facebook Like Button creating divs with CSS styles of -2000px, creating white boxes on site

javascript html facebook html5 facebook-like

I'm using the standard HTML5 FB Like plugin, and all seemed to be well - until I viewed a page on my site that is lengthy, and I noticed two boxes in the middle of my content, well away from the Fa...

"Main method not found" error - what is missing in this code?

java methods main entry-point

I was just re-reading my lecture scripts and trying out the code there. The problem is that the professor gave us only fragments of code and I really stuck on this one. I keep getting this error in