在XML中使用<shape/>标签编辑shape drawable
直接阅读Android官方文档有详细介绍
Android文档Shape Drawable
在Java代码中编辑ShapeDrawable
除了可以在XML文件中编辑的几种shape类型(矩形,椭圆,线条,环),在Java代码中还可以另外设置pathShape类型,ArcShape类型。
//首先获取对应的Shape
Path path = new Path(); //把path放在PathShape中,把PathShape放在ShapeDrawable中
path.moveTo(50,0);
path.lineTo(0,50);
path.lineTo(50,100);
path.lineTo(100,50);
path.lineTo(50,0);
path.close();
PathShape pathShape = new PathShape(path,100,100); //100 100应该覆盖path绘制的范围,否则只是截取左上角的部分。
//将设置好的Shape放入ShapeDrawable中,并设置画笔
ShapeDrawable shapeDrawable = new Drawable(pathShape);
shapeDrawable.getPaint().setStyle(Paint.Style.FILL);
shapeDrawable.getPaint().setColor(Color.BLUE);
//设置为ImageView的背景
(ImageView)findViewById(R.id.path).setBackground(shapeDrawable);
在Java代码中设置ShapeDrawable.ShaderFactory
Drawable尺寸变化时调用ShapeDrawable.ShadeFactory产生的着色器Shader,并将Shader放在画笔Paint上,此时会覆盖了Paint原本的设置。Shader某种程度上就是相当于XML文件中的<gradient/>标签。Shader类型包括以下几种:
- BitmapShader:放了个图片,在绘制时,将图片绘制出来
- LinearGradient,RadialGradient,SweepGradient:与xml中的<gradient/>一直
- ComposeShader:组合效果
Bitmap bitmap = BitmapFactory.decodeResources(this.getResources(),R.mipmap.example);
arcShape = new ArcShape(45,270);
ShapeDrawable shapeDrawable = new ShapeDrawable(arcShape);
shapeDrawable.getPaint().setStyle(Paint.Style.FILL); //
shapeDrawable.getPaint().setColor(Color.RED); //这两行代买都会被Shader覆盖
img.setBackground(shapeDrawable);
shapeDrawable.setShaderFactory(new ShapeDrawable.ShaderFactoty(){
public Shader resize(int width, int height){
return new BitmapShader(bitmap,Shader.TileMode.REPEAT,Shader.TileMode.MIRROR);
}
}
shapeDrawable2.setShaderFactory(new ShapeDrawable.ShaderFactoty(){
public Shader resize(int width,int height){
return new LinearGradient(0,0,width,height,new int[]{
Color.RED,
Color.Green,
Color.BLUE,
Color.YELLOW},
null,Shader.TileMode.REPEAT}); //null是一个浮点数组,与颜色数组对应,分别是每个颜色低位置,0.0 - 1.0;null就是均匀变化
}
}
网友评论