我有一个简短的问题:
假设我有一个(可变)位图需要修改(添加图像、文本等...)。
与其搞乱许多用于在画布上绘制的特殊类(绘画、画布、矩阵等),我在想为什么不使用 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);
}
这样的事情可能吗?也许这就是它在幕后工作的方式?
我应该在绘图和画布创建之间的部分写什么?
编辑:我尝试了下一个代码,但它没有用:
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();
}
用法示例:
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);
编辑:索尼网站上有一个示例:
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);
想知道它是否有效。