Drawable简单使用

本文介绍了Android中Drawable的概念及其用途,详细解释了Drawable作为一种可绘制对象可以是位图、图形或图层。并通过一个自定义View的例子展示了如何使用ShapeDrawable进行简单的绘图操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android文档这样定义Drawable的:

A Drawable is a general abstraction for "something that can be drawn." Most often you will deal with Drawable as the type of resource retrieved for drawing things to the screen; the Drawable class provides a generic API for dealing with an underlying visual resource that may take a variety of forms. Unlike a View , a Drawable does not have any facility to receive events or otherwise interact with the user.

Drawable就是一个可画的对象,其可能是一张位图(BitmapDrawable),也可能是一个图形(ShapeDrawable),还有可能是 一个图层(LayerDrawable),我们根据画图的需求,创建相应的可画对象,就可以将这个可画对象当作一块“画布(Canvas)”,在其上面操作可画对象,并最终将这种可画对象显示在画布上,有点类似于“内存画布“。

下面的一个自定义View显示了ShapeDrawable的一些简单使用方式:

public class TestView extends View { private ShapeDrawable mShapeDrawable; public TestView(Context context) { super(context); int x = 10, y = 10; int width = 300, height = 50; mShapeDrawable = new ShapeDrawable(new OvalShape()); //ShapeDrawable.getPaint():Returns the Paint used to draw the shape mShapeDrawable.getPaint().setColor(Color.YELLOW); mShapeDrawable.setBounds(x, y, x+width, y+height); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); canvas.drawColor(Color.WHITE); mShapeDrawable.draw(canvas); } }

程序运行效果如下图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值