編輯:關於Android編程
本文主要包括以下內容:
其中1,2是兩種不同方式處理圖片圓角的情況。3,是通過Matrix進行圖片縮放,旋轉等。4,是通過Matrix操作圖片的處理,包括去飽和,四角黑影,中心突出等。5,圖片加文字組合顯示。
如果暫時感覺這些看不懂:
先看看這兩篇:
Android自定義控件深入學習 Android生成隨機驗證碼
詳解Android自定義控件屬性TypedArray以及attrs
1、使用Xfermode設置圓角圖片
主要代碼
package com.example.customimage.view; import com.example.customimage.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.View; /** * 自定義View,實現圓角,圓形等效果 */ public class XfermodeImageView extends View { //類型 private int type; private static final int TYPE_CIRCLE = 0; //圓形 private static final int TYPE_RECT = 1; //矩形圓角 //原始圖片 private Bitmap mSrc; //矩形圓角的幅度 private int mRadius; //控件的寬度 private int mWidth; // 控件的高度 private int mHeight; public XfermodeImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public XfermodeImageView(Context context) { this(context, null); } /** * 初始化一些自定義的參數 * * @param context * @param attrs * @param defStyle */ public XfermodeImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.XfermodeImageView, defStyle, 0); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { //原始圖片,在布局裡面獲取 case R.styleable.XfermodeImageView_src: mSrc = BitmapFactory.decodeResource(getResources(), a.getResourceId(attr, 0)); break; //類型屬性選擇 case R.styleable.XfermodeImageView_type: //自定義類型屬性,0是圓形,1是矩形圓角 type = a.getInt(attr, 0);// 默認為Circle break; //矩形圓角幅度的獲取,默認是10dp case R.styleable.XfermodeImageView_borderRadius: mRadius = a.getDimensionPixelSize(attr, (int) TypedValue .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10f, getResources().getDisplayMetrics())); Log.i("Show", String.valueOf(mRadius)); break; } } a.recycle(); } /** * 計算控件的高度和寬度 */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 設置寬度 int specMode = MeasureSpec.getMode(widthMeasureSpec); int specSize = MeasureSpec.getSize(widthMeasureSpec); //match_parent或者設置的精確值獲取 //MeasureSpec.EXACTLY if (specMode == MeasureSpec.EXACTLY) { mWidth = specSize; } else { // 由圖片決定的寬 //getPaddingLeft(),getPaddingRight()這兩個值是控件屬性的向內偏移的距離值,所以的一起計算 //區別於layout_marginLeft,兩個控件的左間距值設置 int desireByImg = getPaddingLeft() + getPaddingRight() + mSrc.getWidth(); // wrap_content if (specMode == MeasureSpec.AT_MOST) { //所以最小的值,寬度的話是左右內偏移距離之和 mWidth = Math.min(desireByImg, specSize); } else mWidth = desireByImg; } // 設置高度,部分解釋同上 specMode = MeasureSpec.getMode(heightMeasureSpec); specSize = MeasureSpec.getSize(heightMeasureSpec); //match_parent或者設置的精確值獲取 //MeasureSpec.EXACTLY if (specMode == MeasureSpec.EXACTLY) { mHeight = specSize; } else { int desire = getPaddingTop() + getPaddingBottom() + mSrc.getHeight(); // wrap_content if (specMode == MeasureSpec.AT_MOST) { mHeight = Math.min(desire, specSize); } else mHeight = desire; } //計算好的寬度以及高度是值,設置進去 setMeasuredDimension(mWidth, mHeight); } /** * 繪制image控件 */ @Override protected void onDraw(Canvas canvas) { switch (type) { // 如果是TYPE_CIRCLE繪制圓形 case TYPE_CIRCLE: //圓形寬度和高度應該一致的,所以也要比較一下大小,取小的值 int min = Math.min(mWidth, mHeight); // 圓形寬度和高度如果不一致,按小的值進行壓縮 mSrc = Bitmap.createScaledBitmap(mSrc, min, min, false); //繪制圓形 canvas.drawBitmap(createCircleImage(mSrc, min), 0, 0, null); break; case TYPE_RECT: canvas.drawBitmap(createRoundConerImage(mSrc), 0, 0, null); break; } } /** * 根據原圖和變長繪制圓形圖片 * * @param source * @param min * @return */ private Bitmap createCircleImage(Bitmap source, int min) { final Paint paint = new Paint(); //防止邊緣的抗鋸齒 paint.setAntiAlias(true); Bitmap target = Bitmap.createBitmap(min, min, Config.ARGB_8888); // 產生一個同樣大小的畫布 Canvas canvas = new Canvas(target); // 首先繪制圓形,除以2就是半徑了 //最主要設置第三個參數為min/2,圓角幅度那麼大就是圓形了 canvas.drawCircle(min / 2, min / 2, min/2, paint); // 使用SRC_IN,參考上面的說明---上下層都顯示。下層居上顯示 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); // 繪制圖片 canvas.drawBitmap(source, 0, 0, paint); return target; } /** * 根據原圖添加圓角 * * @param source * @return */ private Bitmap createRoundConerImage(Bitmap source) { final Paint paint = new Paint(); paint.setAntiAlias(true); Bitmap target = Bitmap.createBitmap(mWidth, mHeight, Config.ARGB_8888); Canvas canvas = new Canvas(target); //繪制矩形 RectF rect = new RectF(0, 0, source.getWidth(), source.getHeight()); //設置圓角幅度 canvas.drawRoundRect(rect, mRadius, mRadius, paint); // 使用SRC_IN,參考上面的說明---上下層都顯示。下層居上顯示 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(source, 0, 0, paint); return target; } }
2、使用BitmapShader設置圓角圖片
package com.example.customimage.view; import com.example.customimage.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader.TileMode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.widget.ImageView; /** * */ public class BitmapShaderImageView extends ImageView { // 圖片的類型,圓形or圓角 private int type; public static final int TYPE_CIRCLE = 0; public static final int TYPE_RECT = 1; //圓角大小的默認值 private static final int BODER_RADIUS_DEFAULT = 10; //圓角的大小 private int mBorderRadius; // 繪圖的Paint private Paint mBitmapPaint; //圓角的半徑 private int mRadius; // 3x3 矩陣,主要用於縮小放大 private Matrix mMatrix; // 渲染圖像,使用圖像為繪制圖形著色 private BitmapShader mBitmapShader; // view的寬度 private int mWidth; //矩形 private RectF mRoundRect; public BitmapShaderImageView(Context context) { this(context, null); } public BitmapShaderImageView(Context context, AttributeSet attrs) { super(context, attrs); mMatrix = new Matrix(); mBitmapPaint = new Paint(); mBitmapPaint.setAntiAlias(true); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BitmapShaderImageView); //矩形圓角幅度的獲取,默認是10dp mBorderRadius = a.getDimensionPixelSize( R.styleable.BitmapShaderImageView_borderRadius, (int) TypedValue .applyDimension(TypedValue.COMPLEX_UNIT_DIP, BODER_RADIUS_DEFAULT, getResources() .getDisplayMetrics())); //自定義類型屬性,0是圓形,1是矩形圓角 type = a.getInt(R.styleable.BitmapShaderImageView_type, TYPE_CIRCLE); a.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // 如果類型是圓形,則強制改變view的寬高一致,以小值為准 if (type == TYPE_CIRCLE) { mWidth = Math.min(getMeasuredWidth(), getMeasuredHeight()); //圓形的半徑 mRadius = mWidth / 2; setMeasuredDimension(mWidth, mWidth); } } // 初始化BitmapShader,獲取到圖片資源 // 等待畫布的准備好,然後在畫布上加上Paint就是了 //就是說圖片的載體是Paint private void setUpShader() { Drawable drawable = getDrawable(); if (drawable == null) { return; } Bitmap bmp = drawableToBitamp(drawable); // 將bmp作為著色器,就是在指定區域內繪制bmp //TileMode.CLAMP 拉伸 mBitmapShader = new BitmapShader(bmp, TileMode.CLAMP, TileMode.CLAMP); float scale = 1.0f; if (type == TYPE_CIRCLE) { // 拿到bitmap寬或高的小值 int bSize = Math.min(bmp.getWidth(), bmp.getHeight()); scale = mWidth * 1.0f / bSize; } else if (type == TYPE_RECT) { if (!(bmp.getWidth() == getWidth() && bmp.getHeight() == getHeight())) { // 如果圖片的寬或者高與view的寬高不匹配,計算出需要縮放的比例;縮放後的圖片的寬高,一定要大於我們view的寬高;所以我們這裡取大值; scale = Math.max(getWidth() * 1.0f / bmp.getWidth(), getHeight() * 1.0f / bmp.getHeight()); } } // shader的變換矩陣,我們這裡主要用於放大或者縮小 // scale * scale 的矩陣 mMatrix.setScale(scale, scale); // 設置變換矩陣 mBitmapShader.setLocalMatrix(mMatrix); // 設置shader mBitmapPaint.setShader(mBitmapShader); } @Override protected void onDraw(Canvas canvas) { if (getDrawable() == null) { return; } setUpShader(); if (type == TYPE_RECT) { //繪制矩形 canvas.drawRoundRect(mRoundRect, mBorderRadius, mBorderRadius, mBitmapPaint); } else { //繪制圓形 canvas.drawCircle(mRadius, mRadius, mRadius, mBitmapPaint); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // 圓角圖片的范圍 if (type == TYPE_RECT) mRoundRect = new RectF(0, 0, w, h); } //drawable轉bitmap private Bitmap drawableToBitamp(Drawable drawable) { //從控件的src獲取背景,也是drawable文件獲取 if (drawable instanceof BitmapDrawable) { BitmapDrawable bd = (BitmapDrawable) drawable; return bd.getBitmap(); } //如果沒有繪圖一個,只不過是空白的圖片 int w = drawable.getIntrinsicWidth(); int h = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, w, h); drawable.draw(canvas); return bitmap; } private static final String STATE_INSTANCE = "state_instance"; private static final String STATE_TYPE = "state_type"; private static final String STATE_BORDER_RADIUS = "state_border_radius"; //屏幕旋轉後,取出保存的值 @Override protected Parcelable onSaveInstanceState() { Bundle bundle = new Bundle(); bundle.putParcelable(STATE_INSTANCE, super.onSaveInstanceState()); bundle.putInt(STATE_TYPE, type); bundle.putInt(STATE_BORDER_RADIUS, mBorderRadius); return bundle; } //屏幕旋轉,變量的保存,因為外面設置值,如果不保存,一旋轉就變成個xml裡面設置的值 @Override protected void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { Bundle bundle = (Bundle) state; super.onRestoreInstanceState(((Bundle) state) .getParcelable(STATE_INSTANCE)); this.type = bundle.getInt(STATE_TYPE); this.mBorderRadius = bundle.getInt(STATE_BORDER_RADIUS); } else { super.onRestoreInstanceState(state); } } //設置矩形圓角幅度後,重新繪制控件 public void setBorderRadius(int borderRadius) { int pxVal = dp2px(borderRadius); if (this.mBorderRadius != pxVal) { this.mBorderRadius = pxVal; invalidate(); } } //設置是圓形還是矩形圓角 public void setType(int type) { if (this.type != type) { this.type = type; if (this.type != TYPE_RECT && this.type != TYPE_CIRCLE) { this.type = TYPE_CIRCLE; } requestLayout(); } } //dp轉px public int dp2px(int dpVal) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, getResources().getDisplayMetrics()); } }
3、滑動旋轉縮放的bimp圖片
package com.example.customimage.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PaintFlagsDrawFilter; import android.graphics.PointF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.ImageView; public class MatrixImageView extends ImageView { private static final int MODE_NONE = 0x00123;// 默認的觸摸模式 private static final int MODE_DRAG = 0x00321;// 拖拽模式 private static final int MODE_ZOOM = 0x00132;// 縮放or旋轉模式 private int mode;// 當前的觸摸模式 private float preMove = 1F;// 上一次手指移動的距離 private float saveRotate = 0F;// 保存了的角度值 private float rotate = 0F;// 旋轉的角度 private float[] preEventCoor;// 上一次各觸摸點的坐標集合 private PointF startPointF, midPointF;// 起點、中點對象 private Matrix currentMatrix, savedMatrix;// 當前和保存了的Matrix對象 //原始圖片 private Bitmap mSrc; //控件的寬度 private int mWidth; // 控件的高度 private int mHeight; private PaintFlagsDrawFilter mDrawFilter; public MatrixImageView(Context context, AttributeSet attrs) { super(context, attrs); // 初始化 init(); } /** * 初始化 */ private void init() { // 實例化對象 currentMatrix = new Matrix(); savedMatrix = new Matrix(); startPointF = new PointF(); midPointF = new PointF(); mDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG); // 模式初始化 mode = MODE_NONE; Drawable drawable = getDrawable(); mSrc = drawableToBitamp(drawable); } /** * 計算控件的高度和寬度 */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 設置寬度 int specMode = MeasureSpec.getMode(widthMeasureSpec); int specSize = MeasureSpec.getSize(widthMeasureSpec); //match_parent或者設置的精確值獲取 //MeasureSpec.EXACTLY if (specMode == MeasureSpec.EXACTLY) { mWidth = specSize; } else { // 由圖片決定的寬 //getPaddingLeft(),getPaddingRight()這兩個值是控件屬性的向內偏移的距離值,所以的一起計算 //區別於layout_marginLeft,兩個控件的左間距值設置 int desireByImg = getPaddingLeft() + getPaddingRight() + mSrc.getWidth(); // wrap_content if (specMode == MeasureSpec.AT_MOST) { //所以最小的值,寬度的話是左右內偏移距離之和 mWidth = Math.min(desireByImg, specSize); } else mWidth = desireByImg; } // 設置高度,部分解釋同上 specMode = MeasureSpec.getMode(heightMeasureSpec); specSize = MeasureSpec.getSize(heightMeasureSpec); //match_parent或者設置的精確值獲取 //MeasureSpec.EXACTLY if (specMode == MeasureSpec.EXACTLY) { mHeight = specSize; } else { int desire = getPaddingTop() + getPaddingBottom() + mSrc.getHeight(); // wrap_content if (specMode == MeasureSpec.AT_MOST) { mHeight = Math.min(desire, specSize); } else mHeight = desire; } //計算好的寬度以及高度是值,設置進去 setMeasuredDimension(mWidth, mHeight); } //drawable轉bitmap private Bitmap drawableToBitamp(Drawable drawable) { //從控件的src獲取背景,也是drawable文件獲取 if (drawable instanceof BitmapDrawable) { BitmapDrawable bd = (BitmapDrawable) drawable; return bd.getBitmap(); } //如果沒有繪圖一個,只不過是空白的圖片 int w = drawable.getIntrinsicWidth(); int h = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, w, h); drawable.draw(canvas); return bitmap; } final Paint paint = new Paint(); @Override protected void onDraw(Canvas canvas) { //消除鋸齒, 圖片旋轉後的鋸齒消除不成功,實在不行圖片邊緣加一些白色像素點 canvas.setDrawFilter(mDrawFilter); //畫經過Matrix變化後的圖 canvas.drawBitmap(mSrc, currentMatrix, null); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN:// 單點接觸屏幕時 savedMatrix.set(currentMatrix); startPointF.set(event.getX(), event.getY()); //單點觸摸是移動模式 mode = MODE_DRAG; preEventCoor = null; break; case MotionEvent.ACTION_POINTER_DOWN:// 第二個點接觸屏幕時 preMove = calSpacing(event); if (preMove > 10F) { savedMatrix.set(currentMatrix); // 計算兩個觸摸點的中點坐標 calMidPoint(midPointF, event); //兩點是旋轉或者縮放模式 mode = MODE_ZOOM; } preEventCoor = new float[4]; preEventCoor[0] = event.getX(0); preEventCoor[1] = event.getX(1); preEventCoor[2] = event.getY(0); preEventCoor[3] = event.getY(1); saveRotate = calRotation(event); break; case MotionEvent.ACTION_UP:// 單點離開屏幕時 case MotionEvent.ACTION_POINTER_UP:// 第二個點離開屏幕時 mode = MODE_NONE; preEventCoor = null; break; case MotionEvent.ACTION_MOVE:// 觸摸點移動時 /* * 單點觸控拖拽平移 */ if (mode == MODE_DRAG) { currentMatrix.set(savedMatrix); float dx = event.getX() - startPointF.x; float dy = event.getY() - startPointF.y; currentMatrix.postTranslate(dx, dy); } /* * 兩點觸控拖放旋轉 */ else if (mode == MODE_ZOOM && event.getPointerCount() == 2) { float currentMove = calSpacing(event); currentMatrix.set(savedMatrix); /* * 指尖移動距離大於10F縮放 */ if (currentMove > 10F) { float scale = currentMove / preMove; currentMatrix.postScale(scale, scale, midPointF.x, midPointF.y); } /* * 保持兩點時旋轉 */ if (preEventCoor != null) { rotate = calRotation(event); r = rotate - saveRotate; currentMatrix.postRotate(r, getMeasuredWidth() / 2, getMeasuredHeight() / 2); } } break; } setImageMatrix(currentMatrix); return true; } float r; /** * 計算兩個觸摸點間的距離 */ private float calSpacing(MotionEvent event) { float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); return (float) Math.sqrt(x * x + y * y); } /** * 計算兩個觸摸點的中點坐標 */ private void calMidPoint(PointF point, MotionEvent event) { float x = event.getX(0) + event.getX(1); float y = event.getY(0) + event.getY(1); point.set(x / 2, y / 2); } /** * 計算旋轉角度 * * @param 事件對象 * @return 角度值 */ private float calRotation(MotionEvent event) { double deltaX = (event.getX(0) - event.getX(1)); double deltaY = (event.getY(0) - event.getY(1)); double radius = Math.atan2(deltaY, deltaX); return (float) Math.toDegrees(radius); } }
4、圖片顏色處理(滑動)
package com.example.customimage.view; import com.example.customimage.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrixColorFilter; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.RadialGradient; import android.graphics.Shader.TileMode; import android.util.AttributeSet; import android.view.View; public class DreamEffectView extends View { private Paint mBitmapPaint, mShaderPaint;// 位圖畫筆和Shader圖形的畫筆 private PorterDuffXfermode mXfermode;// 圖形混合模式 private int x, y;// 位圖起點坐標 //控件的寬度 private int mWidth; // 控件的高度 private int mHeight; //原始圖片 private Bitmap mSrc; //生成暗角的圖片 private Bitmap darkCornerBitmap; public final static int BITMAP_NULL = 0; //原圖 private final static int BITMAP_DEAST = 1; //去飽和 private final static int BITMAP_CENTER = 2; //中心突出 private final static int BITMAP_DARKCORNER = 3; //四角黑暗 private int mnSelectMode = 0; public DreamEffectView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public DreamEffectView(Context context) { this(context, null); } public DreamEffectView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs,defStyle); TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.DreamEffectView, defStyle, 0); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { //原始圖片,在布局裡面獲取 case R.styleable.DreamEffectView_src: mSrc = BitmapFactory.decodeResource(getResources(), a.getResourceId(attr, 0)); break; case R.styleable.DreamEffectView_mode: mnSelectMode = a.getInt(attr, 0); break; } } a.recycle(); // 實例化混合模式 mXfermode = new PorterDuffXfermode(Mode.SCREEN); // 初始化畫筆 initPaint(); } /** * 計算控件的高度和寬度 */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 設置寬度 int specMode = MeasureSpec.getMode(widthMeasureSpec); int specSize = MeasureSpec.getSize(widthMeasureSpec); if (specMode == MeasureSpec.EXACTLY) { mWidth = specSize; } else { int desireByImg = getPaddingLeft() + getPaddingRight() + mSrc.getWidth(); // wrap_content if (specMode == MeasureSpec.AT_MOST) { //所以最小的值,寬度的話是左右內偏移距離之和 mWidth = Math.min(desireByImg, specSize); } else mWidth = desireByImg; } // 設置高度,部分解釋同上 specMode = MeasureSpec.getMode(heightMeasureSpec); specSize = MeasureSpec.getSize(heightMeasureSpec); if (specMode == MeasureSpec.EXACTLY) { mHeight = specSize; } else { int desire = getPaddingTop() + getPaddingBottom() + mSrc.getHeight(); // wrap_content if (specMode == MeasureSpec.AT_MOST) { mHeight = Math.min(desire, specSize); } else mHeight = desire; } x = mWidth / 2 - mSrc.getWidth() / 2; y = mHeight / 2 - mSrc.getHeight() / 2; //計算好的寬度以及高度是值,設置進去 setMeasuredDimension(mWidth, mHeight); } /** * 初始化畫筆 */ private void initPaint() { // 實例化畫筆 mBitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // 實例化Shader圖形的畫筆 mShaderPaint = new Paint(); switch (mnSelectMode) { case BITMAP_NULL: break; case BITMAP_DEAST: // 去飽和、提亮、色相矯正 mBitmapPaint.setColorFilter(new ColorMatrixColorFilter( new float[] { 0.8587F, 0.2940F, -0.0927F, 0, 6.79F, 0.0821F, 0.9145F, 0.0634F, 0, 6.79F, 0.2019F, 0.1097F, 0.7483F, 0, 6.79F, 0, 0, 0, 1, 0 })); break; case BITMAP_CENTER: // 去飽和、提亮、色相矯正 mBitmapPaint.setColorFilter(new ColorMatrixColorFilter( new float[] { 0.8587F, 0.2940F, -0.0927F, 0, 6.79F, 0.0821F, 0.9145F, 0.0634F, 0, 6.79F, 0.2019F, 0.1097F, 0.7483F, 0, 6.79F, 0, 0, 0, 1, 0 })); // 設置徑向漸變,漸變中心當然是圖片的中心也是屏幕中心,漸變半徑我們直接拿圖片的高度但是要稍微小一點 // 中心顏色為透明而邊緣顏色為黑色 mShaderPaint.setShader(new RadialGradient(mWidth / 2, mWidth / 2, mSrc.getHeight() * 7 / 8, Color.TRANSPARENT, Color.BLACK, TileMode.CLAMP)); break; case BITMAP_DARKCORNER: // 去飽和、提亮、色相矯正 mBitmapPaint.setColorFilter(new ColorMatrixColorFilter( new float[] { 0.8587F, 0.2940F, -0.0927F, 0, 6.79F, 0.0821F, 0.9145F, 0.0634F, 0, 6.79F, 0.2019F, 0.1097F, 0.7483F, 0, 6.79F, 0, 0, 0, 1, 0 })); // 根據我們源圖的大小生成暗角Bitmap darkCornerBitmap = Bitmap.createBitmap(mSrc.getWidth(), mSrc.getHeight(), Bitmap.Config.ARGB_8888); // 將該暗角Bitmap注入Canvas Canvas canvas = new Canvas(darkCornerBitmap); // 計算徑向漸變半徑 float radiu = canvas.getHeight() * (2F / 3F); // 實例化徑向漸變 RadialGradient radialGradient = new RadialGradient(canvas.getWidth() / 2F, canvas.getHeight() / 2F, radiu, new int[] { 0, 0, 0xAA000000 }, new float[] { 0F, 0.7F, 1.0F }, TileMode.CLAMP); // 實例化一個矩陣 Matrix matrix = new Matrix(); // 設置矩陣的縮放 matrix.setScale(canvas.getWidth() / (radiu * 2F), 1.0F); // 設置矩陣的預平移 matrix.preTranslate(((radiu * 2F) - canvas.getWidth()) / 2F, 0); // 將該矩陣注入徑向漸變 radialGradient.setLocalMatrix(matrix); // 設置畫筆Shader mShaderPaint.setShader(radialGradient); // 繪制矩形 canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), mShaderPaint); break; default: break; } } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.BLACK); // 新建圖層 int sc = canvas.saveLayer(x, y, x + mSrc.getWidth(), y + mSrc.getHeight(), null, Canvas.ALL_SAVE_FLAG); // 繪制混合顏色 canvas.drawColor(0xcc1c093e); // 設置混合模式 mBitmapPaint.setXfermode(mXfermode); // 繪制位圖 canvas.drawBitmap(mSrc, x, y, mBitmapPaint); // 還原混合模式 mBitmapPaint.setXfermode(null); // 還原畫布 canvas.restoreToCount(sc); switch (mnSelectMode) { case BITMAP_NULL: break; case BITMAP_DEAST: break; case BITMAP_CENTER: // 繪制一個跟圖片大小一樣的矩形 canvas.drawRect(x, y, x + mSrc.getWidth(), y + mSrc.getHeight(),mShaderPaint); break; case BITMAP_DARKCORNER: // 繪制我們畫好的徑向漸變圖 canvas.drawBitmap(darkCornerBitmap, x, y, null); break; default: break; } } }
1)、實現 去飽和、提亮、色相矯正 效果的部分代碼
mBitmapPaint.setColorFilter(new ColorMatrixColorFilter( new float[] { 0.8587F, 0.2940F, -0.0927F, 0, 6.79F, 0.0821F, 0.9145F, 0.0634F, 0, 6.79F, 0.2019F, 0.1097F, 0.7483F, 0, 6.79F, 0, 0, 0, 1, 0 }));
2)、實現中心顏色為透明而邊緣顏色為黑色效果的部分代碼
mShaderPaint.setShader(new RadialGradient(mWidth / 2, mWidth / 2, mSrc.getHeight() * 7 / 8, Color.TRANSPARENT, Color.BLACK, TileMode.CLAMP));
3)、實現四角黑暗效果的部分代碼
// 根據我們源圖的大小生成暗角Bitmap darkCornerBitmap = Bitmap.createBitmap(mSrc.getWidth(), mSrc.getHeight(), Bitmap.Config.ARGB_8888); // 將該暗角Bitmap注入Canvas Canvas canvas = new Canvas(darkCornerBitmap); // 計算徑向漸變半徑 float radiu = canvas.getHeight() * (2F / 3F); // 實例化徑向漸變 RadialGradient radialGradient = new RadialGradient(canvas.getWidth() / 2F, canvas.getHeight() / 2F, radiu, new int[] { 0, 0, 0xAA000000 }, new float[] { 0F, 0.7F, 1.0F }, TileMode.CLAMP); // 實例化一個矩陣 Matrix matrix = new Matrix(); // 設置矩陣的縮放 matrix.setScale(canvas.getWidth() / (radiu * 2F), 1.0F); // 設置矩陣的預平移 matrix.preTranslate(((radiu * 2F) - canvas.getWidth()) / 2F, 0); // 將該矩陣注入徑向漸變 radialGradient.setLocalMatrix(matrix); // 設置畫筆Shader mShaderPaint.setShader(radialGradient); // 繪制矩形 canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), mShaderPaint);
5、圖片 + 文字
package com.example.customimage.view; import com.example.customimage.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.RectF; import android.graphics.Bitmap.Config; import android.graphics.Paint.Style; import android.graphics.Rect; import android.text.TextPaint; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.View; public class ImageViewText extends View{ //類型 private int type; private static final int TYPE_CIRCLE = 0; //圓形 private static final int TYPE_RECT = 1; //矩形圓角 //原始圖片 private Bitmap mImage; //控件的寬度 private int mWidth; // 控件的高度 private int mHeight; //矩形圓角的幅度 private int mRadius; //圖片下面的文字 private String mTitle; private int mTextColor; private int mTextSize; private Rect rect; private Paint mPaint; private Rect mTextBound; public ImageViewText(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ImageViewText(Context context) { this(context, null); } /** * 初始化所特有自定義類型 * * @param context * @param attrs * @param defStyle */ public ImageViewText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ImageViewText, defStyle, 0); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { //獲取圖片 case R.styleable.ImageViewText_image: mImage = BitmapFactory.decodeResource(getResources(), a.getResourceId(attr, 0)); break; //獲取圓形還是方形 case R.styleable.ImageViewText_type: type = a.getInt(attr, 0); break; //獲取文字 case R.styleable.ImageViewText_titleText: mTitle = a.getString(attr); break; //獲取文字的圖片 case R.styleable.ImageViewText_titleTextColor: mTextColor = a.getColor(attr, Color.BLACK); break; //獲取文字的大小 case R.styleable.ImageViewText_titleTextSize: mTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); break; //矩形圓角幅度的獲取,默認是10dp case R.styleable.ImageViewText_borderRadius: mRadius = a.getDimensionPixelSize(attr, (int) TypedValue .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10f, getResources().getDisplayMetrics())); break; } } a.recycle(); rect = new Rect(); mPaint = new Paint(); mTextBound = new Rect(); mPaint.setTextSize(mTextSize); // 計算了描繪字體需要的范圍 mPaint.getTextBounds(mTitle, 0, mTitle.length(), mTextBound); } //測量控件的大小 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //設置寬度 int specMode = MeasureSpec.getMode(widthMeasureSpec); int specSize = MeasureSpec.getSize(widthMeasureSpec); // match_parent , accurate 大小 if (specMode == MeasureSpec.EXACTLY) { mWidth = specSize; } else { // 由圖片決定的寬 int desireByImg = getPaddingLeft() + getPaddingRight() + mImage.getWidth(); // 由字體決定的寬 int desireByTitle = getPaddingLeft() + getPaddingRight() + mTextBound.width(); //wrap_content 大小 if (specMode == MeasureSpec.AT_MOST) { //取小的值 int desire = Math.max(desireByImg, desireByTitle); mWidth = Math.min(desire, specSize); } } //設置高度 specMode = MeasureSpec.getMode(heightMeasureSpec); // match_parent , accurate 大小 if (specMode == MeasureSpec.EXACTLY) { mHeight = specSize; } else { //wrap_content 大小 mHeight = getPaddingTop() + getPaddingBottom() + mImage.getHeight() + mTextBound.height(); } //測量好的大小設置進去 setMeasuredDimension(mWidth, mHeight); } @Override protected void onDraw(Canvas canvas) { // 邊框 mPaint.setStrokeWidth(4); mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(Color.CYAN); canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint); mPaint.setColor(mTextColor); mPaint.setStyle(Style.FILL); //當前設置的寬度小於字體需要的寬度,將字體改為 //繪制文字 if (mTextBound.width() > mWidth) { TextPaint paint = new TextPaint(mPaint); String msg = TextUtils.ellipsize(mTitle, paint, (float) mWidth - getPaddingLeft() - getPaddingRight(), TextUtils.TruncateAt.END).toString(); canvas.drawText(msg, getPaddingLeft(), mHeight - getPaddingBottom(), mPaint); } else { //正常情況,將字體居中 canvas.drawText(mTitle, mWidth / 2 - mTextBound.width() * 1.0f / 2, mHeight - getPaddingBottom(), mPaint); } //計算居中的矩形范圍 rect.left = mWidth / 2 - mImage.getWidth() / 2 + getPaddingLeft(); rect.right = mWidth / 2 + mImage.getWidth() / 2 + getPaddingRight(); rect.top = (mHeight - mTextBound.height()) / 2 - mImage.getHeight() / 2 + getPaddingTop(); rect.bottom = (mHeight - mTextBound.height()) / 2 + mImage.getHeight() / 2 + getPaddingBottom(); switch (type) { // 如果是TYPE_CIRCLE繪制圓形 case TYPE_CIRCLE: //圓形寬度和高度應該一致的,所以也要比較一下大小,取小的值 int min = Math.min(mWidth, mHeight); // 圓形寬度和高度如果不一致,按小的值進行壓縮 mImage = Bitmap.createScaledBitmap(mImage, min, min, false); //繪制圓形 canvas.drawBitmap(createCircleImage(mImage, min), null, rect, null); break; case TYPE_RECT: canvas.drawBitmap(createRoundConerImage(mImage), null, rect, null); break; } } /** * 根據原圖和變長繪制圓形圖片 * * @param source * @param min * @return */ private Bitmap createCircleImage(Bitmap source, int min) { final Paint paint = new Paint(); //防止邊緣的抗鋸齒 paint.setAntiAlias(true); Bitmap target = Bitmap.createBitmap(min, min, Config.ARGB_8888); // 產生一個同樣大小的畫布 Canvas canvas = new Canvas(target); // 首先繪制圓形,除以2就是半徑了 //最主要設置第三個參數為min/2,圓角幅度那麼大就是圓形了 canvas.drawCircle(min / 2, min / 2, min/2, paint); // 使用SRC_IN,參考上面的說明---上下層都顯示。下層居上顯示 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); // 繪制圖片 canvas.drawBitmap(source, 0, 0, paint); return target; } /** * 根據原圖添加圓角 * * @param source * @return */ private Bitmap createRoundConerImage(Bitmap source) { final Paint paint = new Paint(); paint.setAntiAlias(true); Bitmap target = Bitmap.createBitmap(mWidth, mHeight, Config.ARGB_8888); Canvas canvas = new Canvas(target); //繪制矩形 RectF rect = new RectF(0, 0, source.getWidth(), source.getHeight()); //設置圓角幅度 canvas.drawRoundRect(rect, mRadius, mRadius, paint); // 使用SRC_IN,參考上面的說明---上下層都顯示。下層居上顯示 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(source, 0, 0, paint); return target; } }
是不是很全的Android自定義圖片集合,希望大家喜歡。
基本框架類定義了一些公用方法來修改該控件的外觀,其中方法如下:setInitView(View view, LayoutParams layoutParams):設置初始
本文實例講述了Android編程實現讀取手機聯系人、撥號、發送短信及長按菜單操作方法。分享給大家供大家參考,具體如下:1.Andrid項目結構圖↓主要操作圖中紅色方框內的
上一篇文章中學習了android.provider中Telephony類。這一篇文章學習android.telephony包中的類,這些類是android提供給上層調用的
前言現在RecyclerView的應用越來越廣泛了,不同的應用場景需要其作出不同的改變。有時候我們可能需要實現側滑刪除的功能,比如知乎首頁的側滑刪除,又或者長按Item進