Атрибуты Paint не работают на Canvas

#java #android #android-canvas #android-paint

#java #Android #android-canvas #android-paint

Вопрос:

Я пытаюсь создать шрифт white impact с черным контуром (он же «Шрифт Meme»). Я применил логику для обоих текстов, которые нарисованы на Canvas, но она работает только для одного из них. Вот результат, показывающий, о чем я говорю:

введите описание изображения здесь

Вот мой код:

         Canvas canvas = new Canvas(mutableBitmap);

        TextPaint topFillPaint = new TextPaint();
        TextPaint bottomFillPaint = new TextPaint();

        TextPaint topStrokePaint = new TextPaint();
        TextPaint bottomStrokePaint = new TextPaint();

        Typeface typeface = getResources().getFont(R.font.impact);

        topFillPaint.setColor(Color.WHITE);
        topFillPaint.setTextSize(topTextView.getTextSize());
        topFillPaint.setTypeface(typeface);

        topStrokePaint.setStyle(Paint.Style.STROKE);
        topStrokePaint.setStrokeWidth(8);
        topStrokePaint.setColor(Color.BLACK);
        topStrokePaint.setTextSize(topTextView.getTextSize());
        topStrokePaint.setTypeface(typeface);

        bottomFillPaint.setColor(Color.WHITE);
        bottomFillPaint.setTextSize(bottomTextView.getTextSize());
        bottomFillPaint.setTypeface(typeface);

        bottomStrokePaint.setStyle(Paint.Style.STROKE);
        bottomStrokePaint.setStrokeWidth(8);
        bottomStrokePaint.setColor(Color.BLACK);
        bottomStrokePaint.setTextSize(bottomTextView.getTextSize());
        bottomStrokePaint.setTypeface(typeface);

        float topTextMeasurement = topFillPaint.measureText(topText);
        float bottomTextMeasurement = bottomFillPaint.measureText(bottomText);

        StaticLayout topFillLayout = new StaticLayout(topText, topFillPaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
                1.0f, 0.0f, false);
        StaticLayout topStrokeLayout = new StaticLayout(topText, topStrokePaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
                1.0f, 0.0f, false);


        StaticLayout bottomFillLayout = new StaticLayout(bottomText, bottomFillPaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
                1.0f, 0.0f, false);
        StaticLayout bottomStrokeLayout = new StaticLayout(bottomText, bottomStrokePaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
                1.0f, 0.0f, false);

        canvas.translate(0,0);
        topFillLayout.draw(canvas);

        canvas.translate(0,0);
        topStrokeLayout.draw(canvas);

        canvas.translate(0, canvas.getHeight() - 210);
        bottomFillLayout.draw(canvas);

        canvas.translate(0, canvas.getHeight() - 210);
        bottomStrokeLayout.draw(canvas);
  

Обновить

Я прокомментировал

canvas.translate(0, canvas.getHeight() - 210); и bottomFillLayout.draw(canvas); и была нарисована черная граница. Таким образом, либо текст заливки покрывает контур, либо контур не существует при рисовании текста заливки.

Ответ №1:

Чтобы получить желаемое поведение, вам просто нужно удалить второе canvas.translate(0, canvas.getHeight() - 210); .

canvas.translate Вызовы корректируют текущий перевод Canvas (он добавляет к переводу, он не сбрасывает его полностью). Это означает, что canvas.translate(0, 0); на самом деле это не операция, потому что это вообще не меняет перевод (эти строки можно просто удалить). Перевод не сбрасывается после вызовов draw, поэтому это означает, что ваш второй canvas.translate(0, canvas.getHeight() - 210); вызов переводит за пределы экрана (если только высота вашего экрана не меньше 210 * 2 ).

Смотрите android.graphics.Документация Canvas по методу translate для получения дополнительной информации.

Комментарии:

1. Спасибо, Джоуи. Август на HH Android рекомендовал мне удалить 1-й, 2-й и 4-й canvas.translate() вызовы, и по какой-то причине это сработало. Я не уверен, почему.