question

njsokalski avatar image
0 Votes"
njsokalski asked RobCaplan edited

Tiling A VectorDrawable As A Background

I have a very simple VectorDrawable (it is basically just a diagonal line). I want to tile/repeat this as the background property for a GridLayout. I have seen ways to tile bitmap resources, but not other types of drawables. Is there any simple way to tile a VectorDrawable? The only way I can currently come up with to achieve my goal is to just create a png and tile that, but I would prefer to use a VectorDrawable so that I can modify it more easily. Any ideas?

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered

Hello,​

Welcome to our Microsoft Q&A platform!

but I would prefer to use a VectorDrawable so that I can modify it more easily

To tile a VectorDrawable as the background, try creating a custom 'TileDrawable' to achieve the function.

public class TileDrawable : Drawable
{
    private Paint paint;

    public TileDrawable(Drawable drawable, Shader.TileMode tileMode)
    {
        paint = new Paint();
        paint.SetShader(new BitmapShader(getBitmap(drawable), tileMode, tileMode));
    }

    public override int Opacity => (int)Format.Translucent;

    public override void Draw(Canvas canvas)
    {
        canvas.DrawPaint(paint);
    }

    public override void SetAlpha(int alpha)
    {
        paint.Alpha = alpha;
    }

    public override void SetColorFilter(ColorFilter colorFilter)
    {
        paint.SetColorFilter(colorFilter);
    }

    private Bitmap getBitmap(Drawable drawable)
    {
        if (drawable.GetType() == typeof(BitmapDrawable))
            return ((BitmapDrawable)drawable).Bitmap;
        Bitmap bitmap = Bitmap.CreateBitmap(drawable.IntrinsicWidth, drawable.IntrinsicHeight, Bitmap.Config.Argb8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.SetBounds(0, 0, drawable.IntrinsicWidth, drawable.IntrinsicHeight);
        drawable.Draw(canvas);
        return bitmap;
    }
}

Set the background for the layout.

var backgroundDrawable = this.GetDrawable(Resource.Drawable.the_background);
GridLayout layout = FindViewById<GridLayout>(Resource.Id.root);
layout.Background = new TileDrawable(backgroundDrawable, Shader.TileMode.Repeat);

Best Regards,

Jarvan Zhang


If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.