简体   繁体   English

在ImageView /位图上绘制画布

[英]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. 我一直试图在ImageView上绘制Canvas ,但是创建位图后,我的屏幕上看不到任何图像。 The only thing I get is the small circle I've drawn in the onDraw Method. 我唯一得到的是在onDraw方法中绘制的小圆圈。 I want to have the Canvas on the ImageView . 我想在ImageView上使用Canvas

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! 提前致谢!

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. 如果要绘制一个圆,请使用onClick中的canvas.drawCircle将其直接绘制到画布上。

Second, alling setImageBitmap overwrites any previous bitmap you set. 其次,所有setImageBitmap都会覆盖您设置的任何以前的位图。 If you want this to show over the previous image, you have 2 options: 如果希望此图像显示在上一张图像上,则有2个选项:

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). 1)在彼此顶部使用两个图像视图,并将顶部图像设置为在画布上制作的位图(要进行此项工作,您可能需要确保位图上的背景色是透明的)。

2)Create a new view subclassed off ImageView that displays 2 bitmaps by overriding onDraw. 2)创建一个新的视图类,该类从ImageView继承而来,该视图通过覆盖onDraw显示2位图。

The first approach is probably easier. 第一种方法可能更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM