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

Добавление изображения в текстовый фон

Недавно я хотел сделать что-то изящное с моим новым проектом, например, как следует из названия, добавить фоновое изображение в качестве текстового фона, а не типичный постоянный цвет вокруг. В частности, у меня есть градиентное изображение для этого текста.

Что-то вроде этого

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

Как правило, я ожидаю, что решение типа файла с гибким ресурсом xml, но любое простое решение будет оценено

EDIT:

Спасибо за все шейдерные решения, но, ради вопроса, будут приняты только ответы, которые обеспечивают решение, касающееся фоновых изображений.//bounty

4b9b3361

Ответ 1

Вы можете применить BitmapShader к краске TextView.

myTextView.getPaint().setShader(new BitmapShader(myBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));

Существуют и другие типы шейдеров, если вы не хотите использовать изображение. Документация здесь.

Ответ 2

Shader - это класс, основанный на объектах, возвращающих горизонтальные интервалы цветов во время рисования. Подкласс Shader устанавливается в Paint paint.setShader(шейдер). После этого любой объект (кроме растрового изображения), который нарисован этой краской, получит свой цвет (-ы) из шейдера.

        Bitmap bitmapObj  = BitmapFactory.decodeResource(getResources(),R.drawable.your_image);
        Shader shaderObj = new BitmapShader(bitmapObj,Shader.TileMode.REPEAT,Shader.TileMode.REPEAT);
        textViewObj.getPaint().setShader(shaderObj);
        textViewObj.setText("hello");

Вы должны назвать Shader.TileMode

Вы также можете следить за

Ответ 3

Вы можете использовать yourTextView.getPaint().setShader(new LinearGradient(...));

Существует два конструктора для LinearGradient:

/** Create a shader that draws a linear gradient along a line.
    @param x0           The x-coordinate for the start of the gradient line
    @param y0           The y-coordinate for the start of the gradient line
    @param x1           The x-coordinate for the end of the gradient line
    @param y1           The y-coordinate for the end of the gradient line
    @param  colors      The colors to be distributed along the gradient line
    @param  positions   May be null. The relative positions [0..1] of
                                each corresponding color in the colors array. If this is null,
                                the the colors are distributed evenly along the gradient line.
    @param  tile        The Shader tiling mode
*/

public LinearGradient(float x0, float y0, float x1, float y1, int colors[], float positions[], TileMode tile)

и

/** Create a shader that draws a linear gradient along a line.
    @param x0       The x-coordinate for the start of the gradient line
    @param y0       The y-coordinate for the start of the gradient line
    @param x1       The x-coordinate for the end of the gradient line
    @param y1       The y-coordinate for the end of the gradient line
    @param  color0  The color at the start of the gradient line.
    @param  color1  The color at the end of the gradient line.
    @param  tile    The Shader tiling mode
*/
public LinearGradient(float x0, float y0, float x1, float y1, int color0, int color1, TileMode tile)

Документация шейдеров:

https://developer.android.com/reference/android/graphics/Shader.html

Документация Shaders.TileMode:

https://developer.android.com/reference/android/graphics/Shader.TileMode.html


Другой способ (как идея и не протестирован):

Преобразуйте текст в растровое и рисованное, затем используйте GradientDrawable

Ответ 4

создать gradient.xml в папке с возможностью переноса. Вы можете установить угол, начальный и конечный цвет. Установите это значение как фоновый

   <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
     android:shape="rectangle">
     <gradient
    android:startColor="#FFFFFF"
    android:endColor="#00000000"
    android:angle="45"/>    
    </shape>

Ответ 5

Вместо того, чтобы загружать gpu/system, используя шейдеры и прочее, предложенные выше, рекомендуется использовать относительный макет.

<RelativeLayout 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/your_imageview_id"
        android:layout_width="fill_parent"
        android:layout_height="As_you_want_dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:scaleType="fitXY"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/your_textview_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true" />

</RelativeLayout>