How can we tile a vector image?

后端 未结 5 709
眼角桃花
眼角桃花 2021-02-12 21:02

With the support library now fully supporting vector images, I\'m trying to switch to vector images as much as I can in my app. An issue I\'m running into is that it seems impos

5条回答
  •  北海茫月
    2021-02-12 21:20

    This is the java version of Nick Butcher solution:

    import android.graphics.Bitmap;
    import android.graphics.BitmapShader;
    import android.graphics.Canvas;
    import android.graphics.ColorFilter;
    import android.graphics.Paint;
    import android.graphics.PixelFormat;
    import android.graphics.Shader;
    import android.graphics.drawable.BitmapDrawable;
    import android.graphics.drawable.Drawable;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    
    public class TileDrawable extends Drawable {
    
        private final Paint paint;
    
        public TileDrawable(Drawable drawable, Shader.TileMode tileMode) {
            paint = new Paint();
            paint.setShader(new BitmapShader(getBitmap(drawable), tileMode, tileMode));
        }
    
        @Override
        public void draw(@NonNull Canvas canvas) {
            canvas.drawPaint(paint);
        }
    
        @Override
        public void setAlpha(int alpha) {
            paint.setAlpha(alpha);
        }
    
        @Override
        public void setColorFilter(@Nullable ColorFilter colorFilter) {
            paint.setColorFilter(colorFilter);
        }
    
        @Override
        public int getOpacity() {
            return PixelFormat.TRANSLUCENT;
        }
    
        private Bitmap getBitmap(Drawable drawable) {
            if (drawable instanceof BitmapDrawable)
                return ((BitmapDrawable) drawable).getBitmap();
            Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            drawable.draw(canvas);
            return bitmap;
        }
    
    }
    

    You can use this drawable class in code with vector patterns:

    view.setBackground(new TileDrawable(getContext().getDrawable(R.drawable.pattern), Shader.TileMode.REPEAT));
    

提交回复
热议问题