git-osc自己定義控件之:CircleImageView
git-osc自己定義控件之:CircleImageView
一、CircleImageView的使用
在項目中能夠發現,用戶的頭像都是圓形的。感覺非常好奇,昨天最終發現了,原來是自定了一個ImageView。先學習下怎樣使用,使用過程例如以下:
創建屬性文件:
attrs.xml
,創建路徑為——res/values/attrs.xml
。格式例如以下:<?xml version="1.0" encoding="utf-8"?> <resources>
將
CircleImageView.java
復制到項目project中,比方在路徑為:com.nc.view
- 在布局文件裏引入,自己定義控件,代碼例如以下:
<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">
<com .nc.view.CircleImageView
android:id="@+id/circle_img"
android:layout_weight="1"
....
/>
</LinearLayout>
做完上述三步就能夠在自己的項目中使用這個自己定義控件:CircleImageView.java 了。
二、CircleImageView 解析
CircleImageView中使用到的知識點:
TypedArray 、declare-styleable、ColorFilter、ScaleType、Bitmap.Config、Canvas、Matrix、BitmapShaderPaint
TypedArray
Container for an array of values that were retrieved with obtainStyledAttributes(AttributeSet, int[], int, int) or obtainAttributes(AttributeSet, int[]). Be sure to call recycle() when done with them. The indices used to retrieve values from this structure correspond to the positions of the attributes given to obtainStyledAttributes.
包括了一個數組值,這個數組值會被
obtainStyledAttributes(AttributeSet, int[], int, int)
orobtainAttributes(AttributeSet, int[])
方法拿到。可是確保在拿到數組中的值後要調用 recycle()方法。我們能夠通過索引值,在
obtainStyledAttributes
的屬性中檢索相相應的值。
那麽該怎樣使用呢。代碼例如以下:
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.CircleImageView, defStyle, 0);
mBorderWidth = a.getDimensionPixelSize(
R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH);
mBorderColor = a.getColor(R.styleable.CircleImageView_border_color,
DEFAULT_BORDER_COLOR);
a.recycle();
上面就是一個詳細的應用:
- 通過
obtainStyledAttributes
獲取TypedArray
, 其屬性值存放在res/attrs.xml
中的declare-styleable
中,關於declare-styleable
在以下再詳細描寫敘述。 - 通過
TypedArray
提供的一系列方法getXXXX
獲取相應的屬性。 - 拿完屬性之後。要調用
recycle()
。
declare-styleable
如上代碼所看到的,屬性值都是存在了declare-styleable
中,而declare-styleable
則是在 res/attrs.xml
的 <resource>
節點下。代碼詳情例如以下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CircleImageView">
<attr name="border_width" format="dimension" />
<attr name="border_color" format="color" />
</declare-styleable>
</resources>
能夠看到:
通過
name="CircleImageView"
屬性來給declare-styleable
命令。該名字將會在obtainStyledAttributes(attrs,R.styleable.CircleImageView, defStyle, 0)
中使用。通過
<attr .../>
來給CircleImageView
指定屬性:<attr name="xxx".../>
當中的name="xxx"
來指定該屬性的名字;<attr ... format="xxx"/>
當中的format="xxx"
來指定該屬性的類型;
當中的format
共同擁有例如以下類型,能夠參見文章:(format詳細解釋)[http://www.cnblogs.com/622698abc/p/3348692.html]
- reference :參考某一資源ID
- string :字符串
- color :顏色值
- dimension :尺寸值
- boolean :布爾值
- integer :整型值
- float :浮點值
- fraction :百分數
- enum :枚舉值
- flag :位或運算
ColorFilter
色彩過濾器。使用方法:
//初始化Paint。而且設置消除鋸齒。
Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
ColorMatrixColorFilter colorFilter = new ColorMatrixColorFilter(new float[]{
1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0
});
paint.SetColorFilter(colorFilter);
兩篇不錯的關於ColorFilter的博客:
- Android圖像處理——Paint之ColorFilter
- 用ColorFilter為安卓button添加效果
ScaleType
圖片的縮放,共同擁有8個屬性:
matrix、fitXY、fitStart、fitCenter、fitEnd、center、centerCrop、centerInside
詳細使用方法參見博客:
p=189">在android中設置圖片的scaleType屬性
Bitmap.Config
- Bitmap.Config ALPHA_8
- Bitmap.Config ARGB_4444
- Bitmap.Config ARGB_8888
Bitmap.Config RGB_565
A R G B
透明度 紅色 綠色 藍色
Bitmap.Config ARGB_4444 16位每一個像素 占四位
Bitmap.Config ARGB_8888 32位每一個像素 占八位
Bitmap.Config RGB_565 16位R占5位 G占6位 B占5位 沒有透明度(A)
普通情況下我們都是用argb888 可是無可厚非 它也相對的非常占內存
由於一個像素32位 8位一個字節 假設是800*480的圖片的話自己算 預計有1M多了
Canvas
大部分2D使用的api都在android.graphics和android.graphics.drawable包。
他們提供了圖形處理相關的:Canvas、ColorFilter、Point(點)和RetcF(矩形)等。另一些動畫相關的:AnimationDrawable、 BitmapDrawable和TransitionDrawable等。以圖形處理來說,我們最經常使用到的就是在一個View上畫一些圖片、形狀或者自己定義的文本內容,這裏我們都是使用Canvas來實現的。你能夠獲取View中的Canvas對象,繪制一些自己定義形狀。然後調用View. invalidate方法讓View又一次刷新,然後繪制一個新的形狀。這樣達到2D動畫效果。
以下我們就主要來了解下Canvas的使用方法。
Canvas對象的獲取方式有兩種:
- 一種我們通過重寫View.onDraw方法,View中的Canvas對象會被當做參數傳遞過來,我們操作這個Canvas,效果會直接反應在View中。
- 另一種就是當你想創建一個Canvas對象時使用的方法:
Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
通過Canvas繪制的圖形有:弧線(arcs)、填充顏色(argb和color)、 Bitmap、圓(circle和oval)、點(point)、線(line)、矩形(Rect)、圖片(Picture)、圓角矩形 (RoundRect)、文本(text)、頂點(Vertices)、路徑(path)
Canvas提供的位置轉換方法:rorate、scale、translate、skew(扭曲)
Matrix
對於一個圖片變換的處理,須要Matrix類的支持,它位於”android.graphics.Matrix”包下。是Android提供的一個矩陣工具類,它本身不能對圖像或View進行變換。但它可與其它API結合來控制圖形、View的變換,如Canvas。
Matrix提供了一些方法來控制圖片變換:
- setTranslate(float dx,float dy):控制Matrix進行位移。
- setSkew(float kx,float ky):控制Matrix進行傾斜,kx、ky為X、Y方向上的比例。
- setSkew(float kx,float ky,float px,float py):控制Matrix以px、py為軸心進行傾斜,kx、ky為X、Y方向上的傾斜比例。
- setRotate(float degrees):控制Matrix進行depress角度的旋轉,軸心為(0,0)。
- setRotate(float degrees,float px,float py):控制Matrix進行depress角度的旋轉,軸心為(px,py)。
- setScale(float sx,float sy):設置Matrix進行縮放,sx、sy為X、Y方向上的縮放比例。
setScale(float sx,float sy,float px,float py):設置Matrix以(px,py)為軸心進行縮放,sx、sy為X、Y方向上的縮放比例。
之前有提過,圖片在內存中存放的就是一個一個的像素點。而對於圖片的變換主要是處理圖片的每一個像素點,對每一個像素點進行相應的變換,就可以完畢對圖像的變換。
Paint
Paint代表Canvas上的畫刷,主要用於繪制風格,包括畫刷顏色、畫刷筆觸粗細、填充風格等。
大體上能夠分為兩類,一類與圖形繪制相關,一類與文本繪制相關。
BitmapShader
位圖渲染器,使用BitmapShader方法能夠實現圓形、圓角和橢圓的繪制
BitmapShader是Shader的子類。能夠通過Paint.setShader(Shader shader)進行設置、
我們這裏僅僅關註BitmapShader,構造方法:
mBitmapShader = new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP);
參數1:bitmap
參數2。參數3:TileMode;
TileMode的取值有三種:
CLAMP 拉伸
REPEAT 反復
MIRROR 鏡像
以下是代碼部分:
package com.nfschina.circleimageview.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;
import com.nfschina.circleimageview.R;
//繼承自 ImageView
public class CircleImageView extends ImageView {
private static final ScaleType SCALE_TYPE = ScaleType.CENTER_CROP;
private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
// colordrawable_dimension
private static final int COLORDRAWABLE_DIMENSION = 1;
// default_border_width
private static final int DEFAULT_BORDER_WIDTH = 0;
// default_border_color
private static final int DEFAULT_BORDER_COLOR = Color.BLACK;
//
private final RectF mDrawableRect = new RectF();
private final RectF mBorderRect = new RectF();
private final Matrix mShaderMatrix = new Matrix();
private final Paint mBitmapPaint = new Paint();
private final Paint mBorderPaint = new Paint();
private int mBorderColor = DEFAULT_BORDER_COLOR;
private int mBorderWidth = DEFAULT_BORDER_WIDTH;
private Bitmap mBitmap;
private BitmapShader mBitmapShader;
private int mBitmapWidth;
private int mBitmapHeight;
private float mDrawableRadius;
private float mBorderRadius;
private boolean mReady;
private boolean mSetupPending;
public CircleImageView(Context context) {
super(context);
}
public CircleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
super.setScaleType(SCALE_TYPE);
Log.i("circle" , "CircleImageView");
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.CircleImageView, defStyle, 0);
mBorderWidth = a.getDimensionPixelSize(
R.styleable.CircleImageView_border_width, DEFAULT_BORDER_WIDTH);
mBorderColor = a.getColor(R.styleable.CircleImageView_border_color,
DEFAULT_BORDER_COLOR);
a.recycle();
mReady = true;
if (mSetupPending) {
setup();
mSetupPending = false;
}
}
@Override
public ScaleType getScaleType() {
Log.i("circle" , "getScaleType");
return SCALE_TYPE;
}
@Override
public void setScaleType(ScaleType scaleType) {
Log.i("circle" , "setScaleType");
if (scaleType != SCALE_TYPE) {
throw new IllegalArgumentException(String.format(
"ScaleType %s not supported.", scaleType));
}
}
@Override
protected void onDraw(Canvas canvas) {
Log.i("circle" , "onDraw");
if (getDrawable() == null) {
return;
}
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mDrawableRadius,
mBitmapPaint);
if (mBorderWidth != 0) {
canvas.drawCircle(getWidth() / 2, getHeight() / 2, mBorderRadius,
mBorderPaint);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
Log.i("circle", "onSizeChanged");
setup();
}
public int getBorderColor() {
Log.i("circle" , "getBorderColor");
return mBorderColor;
}
public void setBorderColor(int borderColor) {
Log.i("circle" , "setBorderColor");
if (borderColor == mBorderColor) {
return;
}
mBorderColor = borderColor;
mBorderPaint.setColor(mBorderColor);
invalidate();
}
public int getBorderWidth() {
Log.i("circle" , "getBorderWidth");
return mBorderWidth;
}
public void setBorderWidth(int borderWidth) {
Log.i("circle" , "setBorderWidth");
if (borderWidth == mBorderWidth) {
return;
}
mBorderWidth = borderWidth;
setup();
}
/*
* 給ImageView設置圖片的方法就是setImageXXX。無論你是用JAVA代碼設置。還是在XML裏面用src,
* 它最終還是調用JAVA的setImageXXX方法,在這些個方法的最後一定有一個invalidate的方法。讓其調用onDraw。
*
* 它們在設置完圖片之後必然會調用setup方法,事實上這種方法就是一個初始化操作而已, 可是在setup的結束地方也調用了invalidate
*/
@Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
Log.i("circle", "setImageBitmap");
mBitmap = bm;
setup();
}
@Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
Log.i("circle", "setImageDrawable");
mBitmap = getBitmapFromDrawable(drawable);
setup();
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
Log.i("circle", "setImageResource");
mBitmap = getBitmapFromDrawable(getDrawable());
setup();
}
private Bitmap getBitmapFromDrawable(Drawable drawable) {
Log.i("circle" , "getBitmapFromDrawable");
if (drawable == null) {
return null;
}
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
try {
Bitmap bitmap;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION,
COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), BITMAP_CONFIG);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (OutOfMemoryError e) {
return null;
}
}
/*
* 它巧妙的用這個mBitmap為空,假設這個View還沒有被設置圖片則不會運行以下的方法
*
* 這種方法應當是在onMeasure之後調用的。我們知道圖片設置成功之後,一定是在onMeasure之後,
*
* 所以它並沒有逃脫自己定義控件的的邏輯
*
* 1、重寫onMeasure計算或者設置一些高度、寬度等數據,
* 2、重寫onDraw
* 3、重寫onTouch做一些事件處理或者計算,
*
* 它僅僅是通過一個mBitmap的防空來推斷它是在繪制成功之後的做的事情。
*/
private void setup() {
Log.i("circle" , "setup");
if (!mReady) {
mSetupPending = true;
return;
}
//這個mBitmap比較妙,僅僅有當有圖片被設置以後才會開始運行以下的方法。
if (mBitmap == null) {
return;
}
//使用一張位圖作為紋理對某一區域進行填充,比如我們drawCircle,
//它就會對這個circle裏面進行填充,它的兩個參數就是對X,Y軸進行填充的一些規則。
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP,
Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
// 整個圖像的顯示區域:即所有的View大小區域。
mBorderRect.set(0, 0, getWidth(), getHeight());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2,
(mBorderRect.width() - mBorderWidth) / 2);
// 圖片顯示的區域:即View的大小區域減去邊界的大小。
mDrawableRect.set(mBorderWidth, mBorderWidth, mBorderRect.width()
- mBorderWidth, mBorderRect.height() - mBorderWidth);
// 圖片的半徑大小取圖片小邊。
mDrawableRadius = Math.min(mDrawableRect.height() / 2,
mDrawableRect.width() / 2);
updateShaderMatrix();
invalidate();
}
private void updateShaderMatrix() {
Log.i("circle" , "updateShaderMatrix");
float scale;
float dx = 0;
float dy = 0;
mShaderMatrix.set(null);
if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width()
* mBitmapHeight) {
scale = mDrawableRect.height() / (float) mBitmapHeight;
dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
} else {
scale = mDrawableRect.width() / (float) mBitmapWidth;
dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
}
mShaderMatrix.setScale(scale, scale);
mShaderMatrix.postTranslate((int) (dx + 0.5f) + mBorderWidth,
(int) (dy + 0.5f) + mBorderWidth);
mBitmapShader.setLocalMatrix(mShaderMatrix);
}
}
這裏涉及到了自己定義控件的知識,接下來幾天裏。我將重點學習一下自己定義控件,在這個項目裏另一個:
PagerSlidingTabStrip
。接下來學習一下這個。最後,重點總結一下——
自己定義控件的方法
git-osc自己定義控件之:CircleImageView