Подтвердить что ты не робот

Как сделать любое изображение для рисования на холст?

У меня есть короткий вопрос:

Предположим, что у меня есть (изменяемый) растровый рисунок, который мне нужно изменить (добавить изображения, тексты и т.д.).

Вместо того, чтобы возиться со многими специальными классами для рисования на холсте (краска, холст, матрицы и т.д.), я думал, почему бы не использовать встроенные классы 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);

Интересно, работает ли он.

4b9b3361

Ответ 1

Да, вы можете это сделать. Имейте в виду, так как вы не привязываете его к макету, вам нужно его вручную выложить, прежде чем рисовать:

view.layout(0, 0, viewWidth, viewHeight);

И если вы точно не знаете, что именно вы хотите для этих параметров ширины и высоты, вы также можете сначала его измерить:

int widthSpec = MeasureSpec.makeMeasureSpec (ViewGroup.LayoutParams.WRAP_CONTENT, MeasureSpec.UNSPECIFIED;
int heightSpec = MeasureSpec.makeMeasureSpec (400, MeasureSpec.UNSPECIFIED;
view.measure(widthSpec, heightSpec);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

EDIT:

Если вы уже знаете ширину и высоту, вам нужно:

//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();

ИЗМЕНИТЬ еще раз:

Да, проверено. Вы можете попробовать это самостоятельно:

public class DrawingActivity extends Activity {
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Set a Rect for the 200 x 200 px center of a 400 x 400 px area
        Rect rect = new Rect();
        rect.set(100, 100, 300, 300);

        //Allocate a new Bitmap at 400 x 400 px
        Bitmap bitmap = Bitmap.createBitmap(400, 400, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        //Make a new view and lay it out at the desired Rect dimensions
        TextView view = new TextView(this);
        view.setText("This is a custom drawn textview");
        view.setBackgroundColor(Color.RED);
        view.setGravity(Gravity.CENTER);

        //Measure the view at the exact dimensions (otherwise the text won't center correctly)
        int widthSpec = View.MeasureSpec.makeMeasureSpec(rect.width(), View.MeasureSpec.EXACTLY);
        int heightSpec = View.MeasureSpec.makeMeasureSpec(rect.height(), View.MeasureSpec.EXACTLY);
        view.measure(widthSpec, heightSpec);

        //Lay the view out at the rect width and height
        view.layout(0, 0, rect.width(), rect.height());

        //Translate the Canvas into position and draw it
        canvas.save();
        canvas.translate(rect.left, rect.top);
        view.draw(canvas);
        canvas.restore();

        //To make sure it works, set the bitmap to an ImageView
        ImageView imageView = new ImageView(this);
        imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        setContentView(imageView);
        imageView.setScaleType(ImageView.ScaleType.CENTER);
        imageView.setImageBitmap(bitmap);
    }
}