Android Drawable绘图学习笔记
如何獲取 res 中的資源
數(shù)據(jù)包package:android.content.res
主要類:Resources
Android SDK中的簡介:Class for accessing an application’s resources.Class for accessing an application’s resources. This sits on top of the asset manager of the application (accessible through getAssets()) and provides a higher-level API for getting typed data from the assets.
其主要接口按照功能,劃分為以下三部分:
getXXXX()
例如:
int getColor(int id)
Drawable getDrawable(int id)
String getString(int id)? 直接獲取res中存放的資源
InputStream openRawResource(int id)? 獲取資源的數(shù)據(jù)流,讀取資源數(shù)據(jù)
void parseBundleExtras(XmlResourceParser parser, Bundle outBundle)? 從XML文件中獲取數(shù)據(jù)
Resource為每種資源提供了相應的接口來獲取這種資源,除了可以直接獲取資源外,還額外提供了以數(shù)據(jù)流的方式獲取資源,這在以后的應用程序開發(fā)中會經(jīng)常使用,那么如何獲取Resources了,如下:Resources r = this.getContext().getResources();
如何獲取資源中的畫圖對象
數(shù)據(jù)包package:android.graphics.drawable
主要類:Drawable
Android SDK中的簡介: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.
看了以上簡介,發(fā)現(xiàn)Drawable是個virtual class,具體如何畫圖,需要具體分析Drawable的子類,例如:BitmapDrawable
Android SDK中的簡介:A Drawable that wraps a bitmap and can be tiled, stretched, or aligned. You can create a BitmapDrawable from a file path, an input stream, through XML inflation, or from a Bitmap object. It can be defined in an XML file with the?<bitmap>?element.
其主要接口如下:
BitmapDrawable()
BitmapDrawable(Bitmap bitmap)
BitmapDrawable(String filepath)
BitmapDrawable(InputStream is)
void draw(Canvas canvas)
Draw in its bounds (set via setBounds) respecting optional effects such as alpha (set via setAlpha) and color filter (set via setColorFilter).
final Bitmap getBitmap()
final Paint getPaint()
Drawable是個抽象類,在BitmapDrawable中我們就看到位圖的具體操作,在仔細看下BitmapDrawable的構(gòu)造函數(shù),我們就會發(fā)現(xiàn)與Resource中的openRawResource()接口是相對應的,就可以通過以下方法來獲取位圖:
Resources r = this.getContext().getResources();
Inputstream is = r.openRawResource(R.drawable.my_background_image);
BitmapDrawable? bmpDraw = new BitmapDrawable(is);
Bitmap bmp = bmpDraw.getBitmap();
Paint
數(shù)據(jù)包package:android.graphics
Android SDK中的簡介:The Paint class holds the style and color information about how to draw geometries, text and bitmaps. 主要就是定義:畫刷的樣式,畫筆的大小/顏色等。
Typeface
數(shù)據(jù)包 package:android.graphics
Android SDK中的簡介:The Typeface class specifies the typeface and intrinsic style of a font. 主要就是定義:字體。
核心類顯示資源
數(shù)據(jù)包package:android.graphics
主要類:Canvas
Android SDK中的簡介:The Canvas class holds the “draw” calls. To draw something, you need 4 basic components: A Bitmap to hold the pixels, a Canvas to host the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, Path, text, Bitmap), and a paint (to describe the colors and styles for the drawing).
按照結(jié)構(gòu)的功能,將主要接口分為以下3部分:
boolean clipXXXX() Region區(qū)域操作:DIFFERENCE INTERSECT REPLACE REVERSE_DIFFERENCE UNION XOR
void drawXXXX()畫圖函數(shù)
void rotate()? void scale()? void skew() void translate() 畫布操作函數(shù)
Region在這里需要特殊說明下:Region就是一個區(qū)域,也就是畫布(Canvas)中的有效區(qū)域,在無效區(qū)域上draw,對畫布沒有任何改變。
Drawable類
Drawable是一個通用的抽象類,它的目的是告訴你什么東西是可以畫的。你會發(fā)現(xiàn)基于Drawable類擴展出各種繪圖的類,見下面的表格,當然你可以繼承它來創(chuàng)建你自己的繪圖類.
Interfaces
| Animatable | Interface that drawables suporting animations should implement. |
| Drawable.Callback | Implement this interface if you want to create an animated drawable that extends?Drawable. |
Classes
| AnimationDrawable | An object used to create frame-by-frame animations, defined by a series of Drawable objects, which can be used as a View object's background. |
| BitmapDrawable | A Drawable that wraps a bitmap and can be tiled, stretched, or aligned. |
| ClipDrawable | A Drawable that clips another Drawable based on this Drawable's current level value. |
| ColorDrawable | A specialized Drawable that fills the Canvas with a specified color, with respect to the clip region. |
| 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. |
| Drawable.ConstantState | ? |
| DrawableContainer | ? |
| DrawableContainer.DrawableContainerState | ? |
| GradientDrawable | A Drawable with a color gradient for buttons, backgrounds, etc. |
| InsetDrawable | A Drawable that insets another Drawable by a specified distance. |
| LayerDrawable | A Drawable that manages an array of other Drawables. |
| LevelListDrawable | A resource that manages a number of alternate Drawables, each assigned a maximum numerical value. |
| NinePatchDrawable | A resizeable bitmap, with stretchable areas that you define. |
| PaintDrawable | Drawable that draws its bounds in the given paint, with optional rounded corners. |
| PictureDrawable | Drawable subclass that wraps a Picture, allowing the picture to be used whereever a Drawable is supported. |
| RotateDrawable | A Drawable that can rotate another Drawable based on the current level value. |
| ScaleDrawable | A Drawable that changes the size of another Drawable based on its current level value. |
| ShapeDrawable | A Drawable object that draws primitive shapes. |
| ShapeDrawable.ShaderFactory | Base class defines a factory object that is called each time the drawable is resized (has a new width or height). |
| StateListDrawable | Lets you assign a number of graphic images to a single Drawable and swap out the visible item by a string ID value. |
| TransitionDrawable | An extension of LayerDrawables that is intended to cross-fade between the first and second layer. |
有三種方法可以定義和實例化一個Drawable:保存一個圖片到你工程資源中,使用XML文件來描述Drawable屬性或者用一個正常的類去構(gòu)造。下面我們將討論兩種技術(對一個有開發(fā)經(jīng)驗的開發(fā)者來說構(gòu)造并不是最新的技術)。
從資源圖像文件中創(chuàng)建
一個比較簡單的方法是添加一個圖片到你的程序中,然后通過資源文件引用這個文件,支持的文件類型有PNG(首選的) JPG(可接受的)GIF(不建議),顯然這種對于顯示應用程序的圖標跟來說是首選的方法,也可以用來顯示LOGO,其余的圖片可以用在例如游戲中。
把一個圖片資源,添加你的文件到你工程中res/drawable/目錄中去,從這里,你就可以引用它到你的代碼或你的XML布局中,也就是說,引用它也可以用資源編號,比如你選擇一個文件只要去掉后綴就可以了(例如:my_image.png 引用它是就是my_image)。
注意:SDK指出,為了縮小圖片的存儲空間,在Build的時候又可能對圖片進行壓縮,如果不想被壓縮,可以將圖片放在res/raw/目錄中。
SDK給出的例子:
LinearLayout mLinearLayout;protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// Create a LinearLayout in which to add the ImageViewmLinearLayout = new LinearLayout(this);// Instantiate an ImageView and define its propertiesImageView i = new ImageView(this);i.setImageResource(R.drawable.my_image);i.setAdjustViewBounds(true); // set the ImageView bounds to match the Drawable's dimensionsi.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));// Add the ImageView to the layout and set the layout as the content viewmLinearLayout.addView(i);setContentView(mLinearLayout); }獲取Drawable對象:
Resources res = mContext.getResources(); Drawable myImage = res.getDrawable(R.drawable.my_image);?
注意:保持每個資源類型的一至,可以保證你項目狀態(tài)的一致性,就不用擔心有許多不同類型的對象來實例化它。例如:如果使用相同的圖像資源來實例化兩個Drawable對象。然后修改一個Drawables的屬性(例如alpha),然后不幸得是這個效果也會出現(xiàn)在另一個對象上去。所以當處理同一個資源的多個實例對象時,不是直接轉(zhuǎn)換為Drawable,而是應該執(zhí)行tween animation
如何添加資源到ImageView:
<ImageView android:layout_width="wrap_content"android:layout_height="wrap_content"android:tint="#55ff0000"android:src="@drawable/my_image"/> ?從XML文件中創(chuàng)建
到如今,你應該比較熟悉按Android的原則去開發(fā)一個用戶接口,因此,你也應該理解了定義一個XML文件對于對象的作用與靈活的重要性。這個理念無數(shù)次用于Drawables.
如果你想創(chuàng)建一個Drawable對象,而這個對象并不依賴于變量或用戶的交換,把它定義到XML中去應該是一個不錯的方法。即使你期望在你的應用程序中改變其屬性來增加用戶體驗。你應該考慮把對象放入XML中,因為你可以隨時修改其屬性。
當你在你的XML中定義了一個Drawable,保存這個XML文件到你工程目錄下res/drawable目錄中,然后通過調(diào)用Resource.getDrawable()來檢索并實例化,傳遞給它XML文件中的資源ID號。任何Drawable的子類都支持inflate這個方法,這個方法會通過XML來實例化你的程序。任何Drawable都支持XML的擴展來利用特殊的XML屬性來幫助定義對象的屬性,可以查看任何Drawable子類文檔來看如何定義XML文件。
如下定義了一個TransitionDrawable:An extension of LayerDrawables that is intended to cross-fade between the first and second layer. It can be defined in an XML file with the?<transition>?element. Each Drawable in the transition is defined in a nested?<item>. 有關TransitionDrawable的詳細信息查看http://androidappdocs.appspot.com/reference/android/graphics/drawable/TransitionDrawable.html。
將其定義在res/drawable/expand_collapse.xml:
<?xml version="1.0" encoding="utf-8"?> <transition xmlns:android="http://schemas.android.com/apk/res/android"><item android:drawable="@drawable/pic1"/><item android:drawable="@drawable/pic2"/> </transition>下面實例化并處理:
public class MainActivity extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Resources res=getResources();TransitionDrawable trans=(TransitionDrawable )res.getDrawable(R.drawable.expand_collapse);ImageView image = (ImageView)findViewById(R.id.ImageView01);image.setImageDrawable(trans);trans.startTransition(3000);} }ShapeDrawable
當你想去畫一些動態(tài)的二維圖片,一個ShapeDrawable對象可能會對你有很大的幫助。通過ShapeDrawable,你可以通過編程畫出任何你想到的圖像與樣式。
ShapeDrawable繼承了Drawable, 所以你可以調(diào)用Drawable里有的函數(shù),比如視圖的背景,通過setBackgroundDrawable()設置。當然,你可以在自定義的視圖布局中畫你的圖形,因為ShapeDrawable有自己的draw()方法。你可以在View.OnDraw()方法期間創(chuàng)建一個視圖的子類去畫ShapeDrawable。
ShapeDrawable類(像很多其他Drawable類型在android.graphics.drawable包)允許你定義drawable公共方法的各種屬性。有些屬性你可以需要調(diào)整,包括透明度,顏色過濾,不透明度,顏色。
例子:
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);
??? }
顯示:
CustomDrawableView mCustomDrawableView;protectedvoid onCreate(Bundle savedInstanceState){
??? super.onCreate(savedInstanceState);
??? mCustomDrawableView =newCustomDrawableView(this);
???
??? setContentView(mCustomDrawableView);
}
在XML中定義方法:如果你想用XML文件配置來取代原有布局來畫自定義的drawable,于是你自定義的Drawable類必須重載view (Context, AttributeSet) 構(gòu)造函數(shù)。
<com.example.shapedrawable.CustomDrawableView??? android:layout_width="fill_parent"
??? android:layout_height="wrap_content"
??? />
NinePatchDrawable
NinePatchDrawable 繪畫的是一個可以伸縮的位圖圖像,Android會自動調(diào)整大小來容納顯示的內(nèi)容。一個例子就是NinePatch為背景,使用標準的Android按鈕,按鈕必須伸縮來容納長度變化的字符
NinePatchDrawable是一個標準的PNG圖像,它包括額外的1個像素的邊界,你必須保存它后綴為.9.png,并且保持到工程的res/drawable目錄中。
這個邊界是用來確定圖像的可伸縮和靜態(tài)區(qū)域。你可以在左邊和上邊的線上畫一個或多個黑色的1個像素指出可伸縮的部分(你可以需要很多可伸縮部分),它的相對位置在可伸縮部分相同,所以大的部分總是很大的。
你還有可以在圖像的右邊和下邊畫一條可選的drawable區(qū)域(有效的,內(nèi)邊距線)。如果你的視圖對象設置NinePath為背景然后指定特殊的視圖字體,它將自行伸縮使所有的文本來適應根據(jù)右線與底部線設計好的區(qū)域(如果有的話),當然內(nèi)邊距線不包括其中,Android可以使用左邊的線與上面的線來定義一個drawable區(qū)域。
我們來澄清一下這兩條不同的線,左邊跟頂部的線來定義哪些圖像的像素允許在伸縮時被復制。底部與右邊的線用來定義一個相對位置內(nèi)的圖像,視圖的內(nèi)容就放入其中。
使用方法:
<Buttonid="@+id/tiny"??????? android:layout_width="wrap_content"
??????? android:layout_height="wrap_content"
??????? android:layout_alignParentTop="true"
??????? android:layout_centerInParent="true"
??????? android:text="Tiny"
??????? android:textSize="8sp"
??????? android:background="@drawable/my_button_background"/>
<Buttonid="@+id/big"
??????? android:layout_width="wrap_content"
??????? android:layout_height="wrap_content"
??????? android:layout_alignParentBottom="true"
??????? android:layout_centerInParent="true"
??????? android:text="Biiiiiiig text!"
??????? android:textSize="30sp"
??????? android:background="@drawable/my_button_background"/>
總結(jié)
以上是生活随笔為你收集整理的Android Drawable绘图学习笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何让自己升薪
- 下一篇: Android应用开发—数据更新问题的思