Android畫布和圖形繪製—Canvas and Drawables(四)

來源:互聯網
上載者:User

本文譯自:http://developer.android.com/guide/topics/graphics/2d-graphics.html

形狀繪製

在想要動態繪製一些二維圖形的時候,ShapeDrawable對象將會滿足你的需要。用ShapeDrawable對象能夠編程繪製任何能夠想象得到的原始形狀和主題樣式。

ShapeDrawable類是Drawable類的一個子類,因此能夠在任何期望使用Drawable對象的地方使用ShapeDrawable對象---如用setBackgroundDrawable()方法設定View對象的背景。當然,也可以用繪製的形狀作為自己定製的View對象,然後把它添加到你的布局中。因為ShapeDrawable類有自己的draw()方法,所以能夠在View.onDraw()方法執行期間建立一個繪製ShapeDrawable圖形的View子類。以下代碼只是這種處理一個基本的擴充,它用ShapeDrawable對象來繪製一個View視窗:

publicclassCustomDrawableViewextendsView{
      privateShapeDrawable
mDrawable;

      publicCustomDrawableView(Context
context){
      super(context);

      int x
=10;
      int y
=10;
      int width
=300;
      int height
=50;

      mDrawable
=newShapeDrawable(newOvalShape());
      mDrawable.getPaint().setColor(0xff74AC23);
      mDrawable.setBounds(x,
y, x
+ width, y
+ height);
      }

      protectedvoid
onDraw(Canvas canvas){
      mDrawable.draw(canvas);
      }
      }
在上例的構造器中,ShapeDrawable是作為一個OvalShape對象來定義的,然後給它設定了一個顏色和邊框。如果不設定邊框,那麼形狀就不會被繪製;如果沒有設定顏色,那麼預設的顏色是黑色。

用這個定製的View對象,能夠繪製任何想要的形狀。在上面的例子中,我們在一個Activity中用編程的方式繪製了一個形狀:

     
CustomDrawableView mCustomDrawableView;

      protectedvoid
onCreate(Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      mCustomDrawableView
=newCustomDrawableView(this);

      setContentView(mCustomDrawableView);
      }

如果想要從XML布局中,而不是在Activity中來繪製這個定製的圖形,那麼CustomDrawable類必須重寫View(Context, AttributeSet)構造器,該構造器會在從XML中填充View對象時被調用。然後把這個CustomDrawable元素添加到XML中,如:

     
<com.example.shapedrawable.CustomDrawableView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      />

ShapeDrawable類(像在android.graphics.drawable包中的其他一些Drawable類型)允許用公用的方法定義各種屬性。其中有些屬性可能需要調整,包括:透明度、顏色過濾、抖動、不透明和顏色等。

也能夠使用XML定義初始的繪製形狀。更多的資訊,請閱讀繪圖資源(Drawable Resources)文檔中的形狀繪製(Shape Drawables)一節(http://developer.android.com/guide/topics/resources/drawable-resource.html#Shape

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.