应用场景:需要动态画不同大小的图片
ShapeDrawable继承于Drawable ,可以在使用Drawble的地方直接使用ShapeDrawalbe
那么如何在自定义View中使用呢,只要在onDraw方法中调用.draw方法就好。通过构造ShapeDrawable的时候指定 OvalShape椭圆型等。
public class CustomDrawableView extends View { private ShapeDrawable mDrawable; public CustomDrawableView(Context context) { super(context); int x = 10; int y = 10; int width = 300; int height = 50; mDrawable = new ShapeDrawable(new OvalShape()); mDrawable.getPaint().setColor(0xff74AC23); mDrawable.setBounds(x, y, x + width, y + height); } protected void onDraw(Canvas canvas) { mDrawable.draw(canvas); } }像普通view一样使用:
CustomDrawableView mCustomDrawableView; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCustomDrawableView = new CustomDrawableView(this); setContentView(mCustomDrawableView); }