我是 android 编程新手,我想弄清楚的是这个;
在我的布局中,我有一个 TextView、ImageView 和 Button,它们都在一个垂直方向的 LinearLayout 上。
我希望能够在 ImageView 中动态绘制圆圈,而不会干扰我的其余布局( TextView /按钮)。我正在尝试创建一个 Canvas ,并使用 Canvas 中的 drawcircle 函数来设置圆圈的位置。然后以某种方式将该 Canvas 绘制到我的 imageview 上。我无法让它工作,这有什么诀窍吗?还是我的方法根本上是错误的?在不重新创建整个布局的情况下,我将如何在 ImageView 上绘制圆圈?
谢谢!
最佳答案
我遇到了同样的挑战,并得出结论,覆盖 onDraw 至少在一般情况下是行不通的。 My blog解释原因。对我来说效果很好的是:
- 创建一个新的图像位图并将一个全新的 Canvas 附加到它。
- 将图像位图绘制到 Canvas 中。
- 将您想要的所有其他内容绘制到 Canvas 中。
- 将 Canvas 附加到 ImageView。
这是一个代码 fragment :
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:将 Canvas 绘制到 ImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4918079/