Android:将画布绘制到 ImageView [英] Android: Drawing a canvas to an ImageView

查看:32
本文介绍了Android:将画布绘制到 ImageView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 android 编程的新手,我想弄清楚的是这个;

I'm new to android programming and what I'm trying to figure out is this;

在我的布局中,我有一个 TextView、ImageView 和 Button,它们都在一个垂直方向的 LinearLayout 上.

In my layout i have a TextView, ImageView, and Button, all on a vertically oriented LinearLayout.

我希望能够在 ImageView 中动态绘制圆圈,而不会干扰我的其余布局(文本视图/按钮).我正在尝试创建一个画布,并使用画布中的 drawcircle 函数来设置圆的位置.然后以某种方式将该画布绘制到我的图像视图中.我无法让它工作,这有什么窍门吗?还是我的方法从根本上是错误的?我将如何在不重新创建整个布局的情况下向 ImageView 绘制圆圈?

I want to be able to dynamically draw circles in the ImageView, without disturbing the rest of my layout(textview/button). I'm trying to create a canvas, and use the drawcircle function within canvas to set the location of the circle. And then draw that canvas to my imageview in some way. I cannot get this to work, is there a trick to this? Or is my method fundamentally wrong? How would i go about drawing circles to the ImageView without recreating my entire layout?

谢谢!

推荐答案

我遇到了同样的挑战并得出结论,覆盖 onDraw 至少在一般情况下不起作用.我的博客 解释了原因.对我来说效果很好的是以下几点:

I had the same challenge and came to the conclusion that overwriting onDraw will at least in the general case not work. My blog explains the reasons. What worked very well for me is the following:

  1. 创建一个新的图像位图并为其附加一个全新的画布.
  2. 将图像位图绘制到画布中.
  3. 在画布上画出你想要的一切.
  4. 将画布附加到 ImageView.

这是一个代码片段:

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;

ImageView myImageView = ...
Bitmap myBitmap = ...
Paint myRectPaint = ...
int x1 = ...
int y1 = ...
int x2 = ...
int y2 = ...

//Create a new image bitmap and attach a brand new canvas to it
Bitmap tempBitmap = Bitmap.createBitmap(myBitmap.getWidth(), myBitmap.getHeight(), Bitmap.Config.RGB_565);
Canvas tempCanvas = new Canvas(tempBitmap);

//Draw the image bitmap into the cavas
tempCanvas.drawBitmap(myBitmap, 0, 0, null);

//Draw everything else you want into the canvas, in this example a rectangle with rounded edges
tempCanvas.drawRoundRect(new RectF(x1,y1,x2,y2), 2, 2, myPaint);

//Attach the canvas to the ImageView
myImageView.setImageDrawable(new BitmapDrawable(getResources(), tempBitmap));

这篇关于Android:将画布绘制到 ImageView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆