在XML中使用<shape/>標(biāo)簽編輯shape drawable
直接閱讀Android官方文檔有詳細介紹
Android文檔Shape Drawable
在Java代碼中編輯ShapeDrawable
除了可以在XML文件中編輯的幾種shape類型(矩形激才,橢圓瘸恼,線條东帅,環(huán))靠闭,在Java代碼中還可以另外設(shè)置pathShape類型,ArcShape類型阎毅。
//首先獲取對應(yīng)的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應(yīng)該覆蓋path繪制的范圍,否則只是截取左上角的部分碳柱。
//將設(shè)置好的Shape放入ShapeDrawable中,并設(shè)置畫筆
ShapeDrawable shapeDrawable = new Drawable(pathShape);
shapeDrawable.getPaint().setStyle(Paint.Style.FILL);
shapeDrawable.getPaint().setColor(Color.BLUE);
//設(shè)置為ImageView的背景
(ImageView)findViewById(R.id.path).setBackground(shapeDrawable);
在Java代碼中設(shè)置ShapeDrawable.ShaderFactory
Drawable尺寸變化時調(diào)用ShapeDrawable.ShadeFactory產(chǎn)生的著色器Shader莲镣,并將Shader放在畫筆Paint上,此時會覆蓋了Paint原本的設(shè)置涎拉。Shader某種程度上就是相當(dāng)于XML文件中的<gradient/>標(biāo)簽鼓拧。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是一個浮點數(shù)組季俩,與顏色數(shù)組對應(yīng)钮糖,分別是每個顏色低位置,0.0 - 1.0酌住;null就是均勻變化
}
}