Android graphic, what's drawable, it's practice and principle
What is Drawable
Drawable.java中,对drawable有一段注释。drawable是something can be drawn的一个抽象。
我们可以把一个resource对象,变成drawable, 然后显示到屏幕。
drawable正是提供了这样的api 。 drawable和view不一样,它没有任何和user进行交互的能力。
Drawable -
1)作为Android平下通用的图形对象,它可以装载常用格式的图像,比如GIF、PNG、JPG,当然也支持BMP,当然还提供一些高级的可视化对象,比如 渐变、图形等
2) 它还可以往view的canvas上面,直接作图。例如画出各种shape.
Practice
1)的例子
//定义UI组件 final Button b1 = (Button) findViewById(R.id.Button01); b1.setBackgroundResource(R.drawable.a); final Button b2 = (Button) findViewById(R.id.Button02); b2.setBackgroundColor(Color.parseColor("#FF00FF")); final Drawable dra = this.getResources().getDrawable(R.drawable.a); final Drawable drb = this.getResources().getDrawable(R.drawable.b); //定义按钮点击监听器 OnClickListener ocl = new OnClickListener() { @SuppressWarnings("deprecation") @Override public void onClick(View v) { switch (v.getId()) { case R.id.Button01: if(switch1 == true) { b1.setBackgroundDrawable(dra); switch1 = false; } else { b1.setBackgroundDrawable(drb); switch1 = true; } break; } } }; //给按钮们绑定点击监听器 b1.setOnClickListener(ocl);
principle: How drawable element is shown?
在View::draw()的过程中,首先会看看view的mBackground的成员变量,调用该成员变量的setBounds()和draw函数。
绘图的结果,会保存在canvas当中。
1. Draw the background
13675 * 2. If necessary, save the canvas' layers to prepare for fading
13676 * 3. Draw view's content
13677 * 4. Draw children
13678 * 5. If necessary, draw the fading edges and restore layers
13679 * 6. Draw decorations (scrollbars for instance)
13680 */
final Drawable background = mBackground; 13687 if (background != null) { 13688 final int scrollX = mScrollX; 13689 final int scrollY = mScrollY; 13690 13691 if (mBackgroundSizeChanged) { 13692 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 13693 mBackgroundSizeChanged = false; 13694 } 13695 13696 if ((scrollX | scrollY) == 0) { 13697 background.draw(canvas); 13698 } else { 13699 canvas.translate(scrollX, scrollY); 13700 background.draw(canvas); 13701 canvas.translate(-scrollX, -scrollY); 13702 } 13703 }
2)的例子
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); } }
principle of drawing:
类似于1),作图过程中, drawable的draw函数会画图到canvas. 在上面的例子中,作图过程,最终调用的是:
public class OvalShape extends RectShape { /** * OvalShape constructor. */ public OvalShape() {} @Override public void draw(Canvas canvas, Paint paint) { canvas.drawOval(rect(), paint); } }
所以drawable不过是对canvas drawing primitive的一个封装,使得用起来更容易。
reference:
http://developer.android.com/guide/topics/graphics/2d-graphics.html
http://www.cnblogs.com/feisky/archive/2010/01/08/1642567.html
http://developer.android.com/guide/topics/graphics/2d-graphics.html#shape-drawable