BitmapShader填充图形

package com.loaderman.customviewdemo;

import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
import android.view.View;

public class BitmapShaderView extends View {
    private Paint mPaint;
    private Bitmap mBmp;

    public BitmapShaderView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        mBmp = BitmapFactory.decodeResource(getResources(), R.drawable.dog_edge);
        /*
        *       CLAMP  用边缘色彩来填充多余的空间
        *       MIRROR 重复使用镜像模式的图像来填充多余的空间
        *      REPEAT 重复原图像来填充多余的空间
        */
        mPaint.setShader(new BitmapShader(mBmp, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.WHITE);
        //getWidth()用于获取控件宽度,getHeight()用于获取控件高度
        float left = getWidth() / 3;
        float top = getHeight() / 3;
        float right = getWidth() * 2 / 3;
        float bottom = getHeight() * 2 / 3;

        canvas.drawRect(left, top, right, bottom, mPaint);
//        canvas.drawRect(0,0,getWidth(),getHeight(),mPaint);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:gravity="center"
    android:background="@android:color/white"
    >
 <com.loaderman.customviewdemo.BitmapShaderView
     android:layout_width="match_parent"
     android:layout_height="match_parent" />
</LinearLayout>

效果:

说明:

BitmapShader(Bitmap bitmap, TileMode tileX, TileMode tileY) 

bitmap指定图案

tileX指定当X轴超出单张图片大小时所重复的策略

tileY指定当Y轴超出单张图片大小时所使用的重复策略

原文地址:https://www.cnblogs.com/loaderman/p/10212875.html