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); }}
效果:
说明:
BitmapShader(Bitmap bitmap, TileMode tileX, TileMode tileY)
bitmap指定图案
tileX指定当X轴超出单张图片大小时所重复的策略
tileY指定当Y轴超出单张图片大小时所使用的重复策略