29
我有一个简短的问题:如何使任何视图绘制到画布?
假设我有一个(可变的)位图,我需要修改(添加图像,文本等...)。
我想,为什么不使用Android的内置类来完成这个任务,而且只有当我需要真正定制时才会使用很多特殊的类来绘制画布(油漆,画布,矩阵等等)我仍然可以使用画布的操作?
因此,举例来说,为了表现出任何一种观点(即没有父,当然)的位图,我可以打电话给下一个功能:
public void drawViewToBitmap(Bitmap b, View v, Rect rect) {
Canvas c = new Canvas(b);
// <= use rect to let the view to draw only into this boundary inside the bitmap
view.draw(c);
}
这种事可能吗?也许这就是它在幕后工作的方式?
我应该在绘图和创建画布之间的部分写什么?
编辑:我试了下代码,但没有奏效:
final int imageSize = 50;
rect = new Rect(35, 344 , 35 + imageSize, 344 + imageSize);
final ImageView imageView = new ImageView(mContext);
imageView.setImageBitmap(bitmap);
imageView.setScaleType(ScaleType.CENTER_CROP);
drawFromViewToCanvas(imageView, getRect(), canvas);
编辑:使用的
public void drawFromViewToCanvas(final View view, final Rect rect, final Canvas canvas) {
final int widthSpec = View.MeasureSpec.makeMeasureSpec(rect.width(), View.MeasureSpec.EXACTLY);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(rect.height(), View.MeasureSpec.EXACTLY);
view.measure(widthSpec, heightSpec);
// Lay the view out with the known dimensions
view.layout(0, 0, rect.width(), rect.height());
// Translate the canvas so the view is drawn at the proper coordinates
canvas.save();
canvas.translate(rect.left, rect.top);
// Draw the View and clear the translation
view.draw(canvas);
canvas.restore();
}
比如有一个样品上sony's website:
int measureWidth = View.MeasureSpec.makeMeasureSpec(bitmapWidth, View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(bitmapHeight, View.MeasureSpec.EXACTLY);
view.measure(measureWidth, measuredHeight);
view.layout(0, 0, bitmapWidth, bitmapHeight);
view.draw(canvas);
不知道它是否有效。
我提到的矩形应该用于视图被允许绘制的宽度和高度。我可以使用它的宽度和高度吗?另外,绘制到矩形位置的部分在哪里? –
如果你已经知道位置和大小,那就简单多了。查看编辑。 – kcoppock
你确定它有效吗?你有没有尝试过,例如,在textView或imageView上? –