Как установить Imageview и TextViews в качестве обоев?

Я работаю над установкой Text View поверх ImageView в качестве обоев во время выполнения (есть кнопка для того же). Я попробовал следующий код.

TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Sample Text");
textView.buildDrawingCache();
ImageView imageView = (ImageView) findViewById(R.id.myImageView);
imageView.setBackgroundResource(R.drawable.base);
imageView.setImageBitmap(textView.getDrawingCache());
Bitmap mBitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());

    try {
        myWallpaperManager.setBitmap(mBitmap);
        Toast.makeText(MainActivity.this, "Wallpaper set", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        Toast.makeText(MainActivity.this, "Error setting wallpaper", Toast.LENGTH_SHORT).show();
    }

Это показывает черный экран в качестве обоев.

После этого я попытался сделать то же самое через Canvas. Код выглядит следующим образом.

public void setWallpaper(View view) {
    Bitmap mBitmap = drawTextOnBitmap(getApplicationContext(), R.drawable.base, "Testaaaaa");
    WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());

    try {
        myWallpaperManager.setBitmap(mBitmap);
        Toast.makeText(MainActivity.this, "Wallpaper set", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        Toast.makeText(MainActivity.this, "Error setting wallpaper", Toast.LENGTH_SHORT).show();
    }
}

public Bitmap drawTextOnBitmap(Context context, int resId, String text) {

    // prepare canvas
    Resources resources = context.getResources();
    float scale = resources.getDisplayMetrics().density;
    Bitmap bitmap = BitmapFactory.decodeResource(resources, resId);

    android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
    // set default bitmap config if none
    if (bitmapConfig == null) {
        bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
    }
    // resource bitmaps are immutable, so we need to convert it to mutable one
    bitmap = bitmap.copy(bitmapConfig, true);
    Canvas canvas = new Canvas(bitmap);

    // new antialiased Paint
    TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);

    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);

    // text color - #3D3D3D
    paint.setColor(Color.rgb(61, 61, 61));
    // text size in pixels
    paint.setTextSize((int) (bitmap.getHeight() / 64 * scale));
    // text shadow
    paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);

    // set text width to canvas width minus 16dp padding
    int textWidth = canvas.getWidth() - (int) (2 * scale);

    // init StaticLayout for text
    StaticLayout textLayout = new StaticLayout(text, paint, textWidth,
            Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);

    // get height of multiline text
    int textHeight = textLayout.getHeight();

    // get position of text's top left corner
    float x = (bitmap.getWidth() - textWidth) / 2;
    float y = (bitmap.getHeight() - textHeight) / 2;

    // draw text to the Canvas center
    canvas.save();
    canvas.translate(x, y);
    textLayout.draw(canvas);
    canvas.restore();

    return bitmap;
}

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

Я хочу, чтобы вы все внесли предложения здесь. Основная идея здесь состоит в том, чтобы напечатать текст с определенной ориентацией и стилем с изображением на заднем плане и установить его в качестве обоев во время выполнения. Я также открыт для любых идей, где фрагмент с несколькими текстовыми представлениями и изображением изображения установлен в качестве обоев. Я приведу пример изображения ниже.

Любые предложения будут полезны.

Любые предложения будут полезны.

0 ответов

Другие вопросы по тегам