public class ShaderActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ShaderView shaderView = new ShaderView(getApplicationContext());
this.setContentView(shaderView,new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
}
static class ShaderView extends View{
private Bitmap mBitmap;
private Shader linearGradient ;
private Shader composeShader;
private Shader bitmapShader;
private Shader radialGradient;
private Shader sweepGradient;
private Rect rect;
private Paint paint;
public ShaderView(Context context) {
super(context);
InputStream is = context.getResources().openRawResource(R.drawable.ic_launcher);
mBitmap = BitmapFactory.decodeStream(is);
/**
* 注意1:中心坐标是相对canvas的坐标系设置的。下边SweepGradient类似
* 注意2:positions 坐标最小为0,最大为1,只是一个比例,不是具体值
*/
radialGradient = new RadialGradient(140, 100, 50, new int[]{Color.RED,Color.GREEN,Color.BLUE}, new float[]{0f,0.5f,1f}, TileMode.MIRROR);
/**
* 注意3:postion参数,0指的是正常坐标系的0度角方向,顺时针增加. 0.3则为正常坐标系的-360*0.3
而下边中0.3对应的Color.RED指的是从0.3开始有颜色渐变。而在0~0.3之间没有颜色渐变的
同理,0.6指的是从0.3~0.6 Color.RED变为Color.GREEN 0.6时候,颜色为Color.GREEN 再从0.6~0.8 由Color.GREEN变为 Color.BLUE。 0.8的时候为Color.BLUE 0.8~1 依 然为纯Color.BLUE
*/
sweepGradient = new SweepGradient(100, 340, new int[]{Color.RED, Color.GREEN,Color.BLUE},new float[]{0.3f,0.6f,0.8f});
bitmapShader = new BitmapShader(mBitmap, TileMode.REPEAT, TileMode.REPEAT);
/**
*注意4:如果前四个参数设置为 0,0,0,5 这是纵方向重复,反之设为0,0,5,0单横方向重复
*/
linearGradient = new LinearGradient(0, 0, 5, 5, 0x00ffffff, 0xff000000, TileMode.REPEAT);
/**
* 注意5:new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER) 参数和下边的效果是一样的
*/
composeShader = new ComposeShader(bitmapShader, linearGradient, PorterDuff.Mode.SRC_OVER);
rect = new Rect();
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
rect.set(0, 0, 200, 200);
paint.setShader(radialGradient);
canvas.drawRect(rect, paint);
rect.set(240, 0, 480, 200);
/**
* 注意6:TileMode.REPEAT 和 TileMode.MIRROR 都是重复叠。但是TileMode.CLAMP指的是如果shader不注意画满区间,以边缘颜色填充
*/
paint.setShader(new RadialGradient(340, 100, 50, new int[]{Color.RED,Color.GREEN,Color.BLUE}, new float[]{0f,0.5f,1f}, TileMode.CLAMP));
/**
* 注意7:如果设置了Shader 再设置color是没有效果的
*/
paint.setColor(Color.RED);
canvas.drawRect(rect, paint);
rect.set(0, 240, 200, 480);
paint.setShader(sweepGradient);
canvas.drawRect(rect, paint);
rect.set(240,240,480,480);
paint.setShader(bitmapShader);
canvas.drawRect(rect, paint);
rect.set(0,500,200,700);
paint.setShader(linearGradient);
canvas.drawRect(rect, paint);
rect.set(220,500,480,700);
paint.setShader(composeShader);
canvas.drawRect(rect, paint);
}
}
}
个人感觉shader一般用来绘制背景图的时候用处比较大