У меня есть короткий вопрос:
Предположим, что у меня есть (изменяемый) растровый рисунок, который мне нужно изменить (добавить изображения, тексты и т.д.).
Вместо того, чтобы возиться со многими специальными классами для рисования на холсте (краска, холст, матрицы и т.д.), я думал, почему бы не использовать встроенные классы 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);
}
Возможно ли такое? может быть, даже так, как он работает за кулисами?
что я должен писать в части между рисунком и созданием холста?
EDIT: я пробовал следующий код, но он не работал:
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);
EDIT: есть образец на сайте sony:
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);
Интересно, работает ли он.