int getcolor = Resources.getSystem().getColor(android.R.color.holo_green_light);
Button btn = (Button) findViewById(R.id.btn);
btn.setBackgroundColor(getcolor);
btn.setBackgroundColor(Color.argb(0xff, 0x00, 0x00, 0x00));
setTextColor(Color.parseColor(getActivity().getString(R.string.ui_green)));
//方法一
tv2.setTextColor(android.graphics.Color.RED);
//方法二
//tv2.setTextColor(0xffff00ff); 必須是 8個的不接受6個的
//方法三
//tv2.setTextColor(this.getResources().getColor(R.color.red));
//通過獲得資源文件進行設置。根據不同的情況R.color.red也可以是R.string.red或者R.drawable.red,當然前提是需要在相應的配置文件里做相應的配置,
我們在使用的時候把圖片直接放在文件中,然后直接設置為背景,但是有時候需要控制對齊方式,控制背景如何平鋪——BitmapDrawable
Drawable :一種可以再Canvas 上進行繪制的圖像概念,但是它又不全是圖片,通過顏色也可以構造出各式各樣的圖像效果, Drawable 使用簡單,比自定義View 的成本要低,另外非圖片類型的Drawable占用空間較小,這對減少APK體積有好處
Drawable 在實際開發中,常備用作View的背景或者作為ImageView中的圖像顯示
Canvas : 畫布,一般理解為一種處理過程,使用各種方法來管理Bitmap .GL或者Path路徑
提供了裁剪,選取等操作,
Canvas主要用于2D繪圖,那么它也提供了很多相應的drawXxx()方法,方便我們在Canvas對象上畫畫,drawXxx()具有多種類型,可以畫出:點、線、矩形、圓形、橢圓、文字、位圖等的圖形,這里就不再一一介紹了,只介紹幾個Canvas中常用的方法:void drawBitmap(Bitmap bitmap,float left,float top,Paint paint):android系統不允許直接修改原圖,類似Photoshop中的鎖定,必須通過原圖創建一個同樣大小的Bitmap,并將原圖繪制到該Bitmap中,以一個副本的形式來修改圖像。代碼如下,bm為原圖,bmp為創建的副本。
Bitmap bmp = Bitmap.createBitmap(bm.getWidth(),bm.getHeight(),Bitmap.Config.ARGB_8888);Canvas canvas = new Canvas(bmp);Paint paint = new Paint();canvas.drawBitmap(bm,0,0,paint);
void drawLine(float startX,float startY,float stopX,float stopY,Paint paint):根據給定的起始點和結束點之間繪制連線void drawPath(Path path,Paint paint):根據給定的path,繪制連線void drawPoint(float x,float y,Paint paint):根據給定的坐標,繪制點void drawText(String text,int start,int end,Paint paint):根據給定的坐標,繪制文字int getHeight():得到Canvas的高度int getWidth():得到Canvas的寬度
Paint
我們可以把它看做一個畫圖工具,比如畫筆、畫刷。他管理了每個畫圖工具的字體、顏色、樣式,主要用于設置繪圖風格,包括畫筆顏色、畫筆粗細、填充風格等。如果涉及一些Android游戲開發、顯示特效可以通過這些底層圖形類來高效實現自己的應用。 Paint中提供了大量設置繪圖風格的方法,這里僅列出一些常用的:setARGB(int a,int r,int g,int b):設置ARGB顏色。setColor(int color):設置顏色。setAlpha(int a):設置透明度。setPathEffect(PathEffect effect):設置繪制路徑時的路徑效果。setShader(Shader shader):設置Paint的填充效果。setAntiAlias(boolean aa):設置是否抗鋸齒。setStrokeWidth(float width):設置Paint的筆觸寬度。setStyle(Paint.Style style):設置Paint的填充風格。setTextSize(float textSize):設置繪制文本時的文字大小。setXfermode(Xfermode xfermode):設置繪制的渲染模式
四、Canvas,Drawable,Paint關系
Canvas就是一張畫布,上面可以讓你畫你想畫的東西,你可以想像成他就是小畫家工具。那畫完以后怎么辦?很簡單,把它裝到容器里面,容器有哪些?就是我們前面講的ImageView、GridView、ListView…等等,這是系統幫我們做好的容器,不過這次是存成屬于自己的View,講白話一點就是把我們畫的東西包成一個容器,容器里面裝的是我們的畫布。每個Drawable都會有一個draw的方法,它就是會幫你把這些圖形貼到畫布上面,然后再裝到自定的容器View里面,最后就變成一種容器,看你是要裝進系統的容器或者直接呈現出來都可以。Paint就是畫筆,你在小畫家上面畫畫的時候,都會選擇畫筆來作畫,像什么顏色啊,粗細啊之類的屬性,像上面的例子當中,我們取得Drawable的畫筆,然后將畫筆的顏色改成藍色,這樣畫出來的顏色就會變成藍色的矩形了。那是畫在哪邊?當然是畫布上面,通常Paint都會跟在Drawable的相關類別或者自定View類別一起使用。
五、Canvas的使用方式
以下參考Andriod中繪(畫)圖----Canvas的使用詳解Canvas的兩種使用情形,從Canvas對象的獲得角度分析:
1、 自定義View和自定義SurfaceView中獲得Canvas對象由于自定義View和SurfaceView在顯示界面中已經獲得了顯示區域,canvas對象只不過是在其顯示(繪畫)區域進行界面布局的設計,當操作完畢后,系統會顯示canvas的操作結果。自定義View的繪圖方法為:
//存在canvas對象,即存在默認的顯示區域@Overridepublic void draw(Canvas canvas) {//canvas繪圖}
2、在其他情形下,我們需要通過代碼創建一個Canvas對象,并且在繪畫成功后,將該畫圖區域轉換為Drawable圖片或者通過setBitmap(bitmap)顯現出來。一般步驟為:
//創建一個的Bitmap對象Bitmap bitmap = Bitmap.createBitmap(200, 100, Config.ARGB_8888);//創建一個canvas對象,并且開始繪圖Canvas canvas = new Canvas (bitmap);ImageView imgView = new ImageView(this);//或者其他可以設置背景圖片的View控件//為ImageView設置圖像//將Bitmap對象轉換為Drawable圖像資Drawable drawable = new BitmapDrawable(bitmap);imgView .setBackgroundDrawable(drawable);//或者簡單點:imgView.setImageBitmap(bitmap);
六、【Android】Drawable、Bitmap、Canvas、Paint之間區別
(1)Bitmap 轉化為 byte
ByteArrayOutputStream out = new ByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);byte[] array= out.toByteArray();
(2)byte轉化為bitmap
private Bitmap Bytes2Bimap(byte[] b){if(b.length!=0){return BitmapFactory.decodeByteArray(b, 0, b.length);}else {return null;}}
(3)bitmap 轉換 drawable
Bitmap bitmap = new Bitmap(...);Drawable drawable = new BitmapDrawable(bitmap);//Drawable drawable = new FastBitmapDrawable(bitmap);
(4)Drawable to Bitmap
public static Bitmap drawableToBitmap(Drawable drawable) {Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(),drawable.getOpacity() != PixelFormat.OPAQUE ?Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565);Canvas canvas = new Canvas(bitmap);//canvas.setBitmap(bitmap);drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());drawable.draw(canvas);return bitmap;}
七、自定義Drawable
通常我們沒有必要自定義Drawable,這是因為自定義的Drawable無法在XML中使用,使用范圍有限。如果要自定義Drawable,draw、setAlpha、setColorFilter、getOpacity這幾個方法必須要實現。以下是個圓形的drawable,半徑會隨著view的變化而變化。
public class CustomDrawable extends Drawable{private Paint mPaint;public CustomDrawable(int color){mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);mPaint.setColor(color);}@overridepublic void draw(Canvas canvas){final Rect r = getBounds();float cx = r.exactCenterX();float cy = r.exxactCenterY();canvas.drawCircle(cx,cy,Math.min(cx,cy),mPaint);}@overridepublic void setAlpha(int alpha){mPaint.setAlpha(alpha);invalidateSelf();}@overridepublic void setColorFilter(ColorFilter cf){mPaint.setColorFilter(cf);invalidateSelf();}@overridepublic int getOpacity(){return PixelFormat.TRANSLUCENT;}}
八、Android中的13種Drawable小結
1.BitmapDrawable參考Drawable子類之—— BitmapDrawable (可控制對齊平鋪的圖像)
<?xml version="1.0" encoding="utf-8"?><bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/image1" android:tileMode="repeat" />
2.NinePatchDrawable
<?xml version="1.0" encoding="utf-8"?><nine-patch xmlns:android="http://schemas.android.com/apk/res/android android:dither="false" android:src="@drawable/a" />
注意:@drawable/a中的a圖片就是drawable中a.9.png圖片
3.ShapeDrawable參考Drawable子類之—— ShapeDrawable (圖形定義)通過顏色來構造圖片,可以是純色,也可以是漸變色。比如給按鈕背景圖(純色背景、帶邊框、圓角)可以用shape而不是Png圖片:
[圖片上傳中。。。(1)]Paste_Image.png
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape> <stroke android:width="0.5dp" android:color="@color/white"/> <gradient android:startColor="#ffffff" android:endColor="#ffffff" android:angle="0.0" /> <corners android:topLeftRadius="4dp" android:topRightRadius="0dp" android:bottomLeftRadius="4dp" android:bottomRightRadius="0dp" /> </shape> </item></selector>
4.LayerDrawable參考Drawable子類之——LayoutDrawable (圖層疊加)層次化的drawable集合,有疊加效果。使用item標簽來表示一個Drawable,可以有多個item.有些需求中需要一種圖片,但是明顯這個圖片是其他幾個圖片簡單疊加而已,那么可以使用layer-list來達到目的.
[圖片上傳中。。。(2)]Paste_Image.png
<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <rotate android:pivotX="0" android:pivotY="0" android:fromDegrees="-10" android:toDegrees="-10"> <bitmap android:src="@drawable/chatting_bg_default_thumb"/> </rotate> </item> <item> <rotate android:pivotX="0" android:pivotY="0" android:fromDegrees="15" android:toDegrees="15"> <bitmap android:src="@drawable/chatting_bg_purecolor_thumb"/> </rotate> </item> <item> <rotate android:pivotX="0" android:pivotY="0" android:fromDegrees="35" android:toDegrees="55"> <bitmap android:src="@drawable/mark"/> </rotate> </item></layer-list>
5.StateListDrawable也是一個drawable集合,每個Drawable對應view一個狀態,系統會根據當前View的狀態從selector中選擇對應的item
<selector...><item...><item...><item...></selector>
6.LevelListDrawabledrawable集合,里面每個drawable都對應一個等級。通過setLevel方法設置不同等級可以切換具體的drawable。
7.TransitionDrawable參考Drawable子類之——TransitionDrawable (漸變)
[圖片上傳中。。。(3)]transition.gif
transition_simple.xml<?xml version="1.0" encoding="utf-8"?><transition xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@mipmap/pic1" /> <item android:drawable="@mipmap/pic2" /></transition>import android.app.Activity;import android.graphics.drawable.TransitionDrawable;import android.os.Bundle;import android.widget.ImageView;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView image = (ImageView) findViewById(R.id.mIv); //得到一個Drawable,屬于 TransitionDrawable 類型的 TransitionDrawable transition = (TransitionDrawable)getResources(). getDrawable(R.drawable.transition_simple); image.setImageDrawable(transition); transition.startTransition(2000); // 設定漸變的變化市場 }}
8.InsetDrawable參考Drawable子類之——InsetDrawable (嵌入)將其它Drawable嵌入自己當中,并可以在四周留出一定的間距。InsetDrawable對應的標簽是<inset>他可以將其他的Drawable內嵌到自己的里面。個人覺得其實沒什么用,他能做到的,LayerDrawable也能做,或者有的時候直接設置一下padding就可以了。
[圖片上傳中。。。(4)]Paste_Image.png
insetdrawable_simple.xml<?xml version="1.0" encoding="utf-8"?><inset xmlns:android="http://schemas.android.com/apk/res/android" android:insetBottom="60dp" android:insetLeft="30dp" android:insetRight="30dp" android:insetTop="60dp" > <shape android:shape="rectangle" > <solid android:color="#0000ff" /> </shape></inset><?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ImageView android:id="@+id/mIv" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" android:background="@mipmap/op" android:src="@drawable/insetdrawable_simple" /></RelativeLayout>
9.ScaleDrawable根據自己的等級將指定的drawable縮放到一定比例。
<scale...
10.ClipDrawable參考Drawable子類之——ClipDrawable (裁剪圖像)根據當前等級裁剪一個Drawable,裁剪方向受clipOrientation和gravity兩個屬性共同控制。
[圖片上傳中。。。(5)]Paste_Image.png
clipdrawable_simple.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <ImageView android:layout_width="200dp" android:layout_height="200dp" android:background="@mipmap/star" android:layout_marginBottom="20dp"/> <ImageView android:id="@+id/mIvClip" android:layout_width="200dp" android:layout_height="200dp" android:background="@drawable/clipdrawable_simple" /></LinearLayout>import android.app.Activity;import android.graphics.drawable.ClipDrawable;import android.os.Bundle;import android.widget.ImageView;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imageView = (ImageView) findViewById(R.id.mIvClip); //ClipDrawable clipDrawable = (ClipDrawable) imageView.getDrawable(); 這樣寫會報空指針異常 ClipDrawable clipDrawable = (ClipDrawable) imageView.getBackground(); clipDrawable.setLevel(5000); }}
11.RotateDrawable這里兩個圖片是兩個按鈕箭頭,但是僅僅方向不同而已,其實可以只用其中一個圖片即可,而另一個用RotateDrawable來讓其“調轉”180度
[圖片上傳中。。。(6)]Paste_Image.png
<?xml version="1.0" encoding="utf-8"?><rotate xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/ic_arrow_left" android:fromDegrees="180" android:pivotX="50%" android:pivotY="50%" android:toDegrees="180" />
1.5、在Android中得到一個Bitmap對象的方法
1.5.1、使用常用的靜態方法獲取Bitmap對象:
static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height, Matrix m, boolean filter)
//Returns an immutable bitmap from subset of the source bitmap, transformed by the optional matrix.
static Bitmap createBitmap(int width, int height, Bitmap.Config config)
//Returns a mutable bitmap with the specified width and height.
static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height)
//Returns an immutable bitmap from the specified subset of the source bitmap.
static Bitmap createBitmap(int[] colors, int offset, int stride, int width, int height, Bitmap.Config config)
//Returns a immutable bitmap with the specified width and height, with each pixel value set to the corresponding value in the colors array.
static Bitmap createBitmap(Bitmap src)
//Returns an immutable bitmap from the source bitmap.
static Bitmap createBitmap(int[] colors, int width, int height, Bitmap.Config config)
//Returns a immutable bitmap with the specified width and height, with each pixel value set to the corresponding value in the colors array.
static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)
//Creates a new bitmap, scaled from an existing bitmap, when possible.
1.5.2、使用BitmapFactory工廠類獲取Bitmap對象
BitmapFactory工廠類是一個工具類,提供了大量的方法,大多數是從不同的數據源來解碼、創建Bitmap對象,典型方法如下。
static Bitmap decodeByteArray(byte[] data, int offset, int length, BitmapFactory.Options opts)
//Decode an immutable bitmap from the specified byte array.
//解析byte[]
static Bitmap decodeByteArray(byte[] data, int offset, int length)
//Decode an immutable bitmap from the specified byte array.
static Bitmap decodeFile(String pathName)
//Decode a file path into a bitmap.
static Bitmap decodeFile(String pathName, BitmapFactory.Options opts)
//Decode a file path into a bitmap.
static Bitmap decodeFileDescriptor(FileDescriptor fd)
//Decode a bitmap from the file descriptor.
static Bitmap decodeFileDescriptor(FileDescriptor fd, Rect outPadding, BitmapFactory.Options opts)
//Decode a bitmap from the file descriptor.
static Bitmap decodeResource(Resources res, int id, BitmapFactory.Options opts)
//Synonym for opening the given resource and calling decodeResourceStream(Resources, TypedValue, InputStream, Rect, BitmapFactory.Options).
static Bitmap decodeResource(Resources res, int id)
//Synonym for decodeResource(Resources, int, android.graphics.BitmapFactory.Options) will null Options.
static Bitmap decodeResourceStream(Resources res, TypedValue value, InputStream is, Rect pad, BitmapFactory.Options opts)
//Decode a new Bitmap from an InputStream.
static Bitmap decodeStream(InputStream is)
//Decode an input stream into a bitmap.
static Bitmap decodeStream(InputStream is, Rect outPadding, BitmapFactory.Options opts)
//Decode an input stream into a bitmap.
1.5.3、使用BitmapDrawable獲取Bitmap對象
BitmapDrawable繼承于Drawable
//方法一
Resources res;
InputStream is=res.openRawResource(R.drawable.pic);
BitmapDrawable bitmapDrawable=new BitmapDrawable(is);
Bitmap bmp=bitmapDrawable.getBitmap();
//方法二
Resources res;
BitmapDrawable bitmapDrawable=(BitmapDrawable)res.getDrawable(R.drawable.pic);
Bitmap bmp=bitmapDrawable.getBitmap();
//方法三
ImageView image;
image.setImageBitmap(BitmapFactory.decodeStream(~~~~));
BitmapDrawable bitmapDrawable=(BitmapDrawable)image.getDrawable();
Bitmap bmp=bitmapDrawable.getBitmap();
1.6、附上Bitmap與byte[]的轉換關系
1.6.1、Bitmap2Bytes
public byte[] Bitmap2Bytes(Bitmap bmp) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//public boolean compress (Bitmap.CompressFormat format, int quality, OutputStream stream)
bmp.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream );
return byteArrayOutputStream.toByteArray();
}
1.6.2、Bytes2Bitmap
static Bitmap decodeByteArray(byte[] data, int offset, int length, BitmapFactory.Options opts)
//Decode an immutable bitmap from the specified byte array.
//解析byte[]