Android 自定义形状ImageView

时间:2021-03-06 20:37:13
使用方法:在xml文件中,在src中传入形状的图片,然后再代码中调用setImageBitmap(bitmap)方法,传入显示的bitmap,
xml中,layout_width和layout_height属性不能为full_parent

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

/**
* Created by huangqiyu on 2016/8/19.
*/
public class CustomShapeImageView extends ImageView {
Context mContext;
Bitmap mBitmapShape;
private int mWidth;
private int mHeight;
private Paint paint;
private Bitmap mBitmap;
private Matrix mMatrixShape;
private Matrix mMatrixPic;


public CustomShapeImageView(Context context) {
this(context, null);
}

public CustomShapeImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public CustomShapeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
mMatrixShape = new Matrix();
mMatrixPic = new Matrix();
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = getMeasuredWidth();
mHeight = getMeasuredHeight();
setBitmapByExactly(mBitmap);
}

@Override
protected void onDraw(Canvas canvas) {
if (mBitmapShape == null) {
super.onDraw(canvas);
} else {
canvas.drawBitmap(mBitmapShape, 0, 0, null);
}
}

public void setImageBitmap(Bitmap bitmap) {
mBitmap = bitmap;
}

/**
* xml中width和height设置为warp_parent或具体数值时
*
* @param bitmap 设置显示的Bitmap
*/
private void setBitmapByExactly(Bitmap bitmap) {
Bitmap bitmapPic = bitmap.copy(Bitmap.Config.ARGB_8888, true);
BitmapDrawable bitmapDrawable = (BitmapDrawable) getDrawable();
mBitmapShape = bitmapDrawable.getBitmap().copy(Bitmap.Config.ARGB_8888, true);

float scaleShapeWidth = mWidth / ((float) mBitmapShape.getWidth());
float scaleShapeHeight = mHeight / ((float) mBitmapShape.getHeight());
float scalePicWidth = mWidth / ((float) bitmapPic.getWidth());
float scalePicHeight = mHeight / ((float) bitmapPic.getHeight());

mMatrixShape.postScale(scaleShapeWidth, scaleShapeHeight);
mMatrixPic.postScale(scalePicWidth, scalePicHeight);
mBitmapShape = Bitmap.createBitmap(mBitmapShape, 0, 0, mBitmapShape.getWidth(), mBitmapShape.getHeight(), mMatrixShape, true);
Bitmap bitmapPicResize = Bitmap.createBitmap(bitmapPic, 0, 0, bitmapPic.getWidth(), bitmapPic.getHeight(), mMatrixPic, true);

Canvas canvas = new Canvas(mBitmapShape);
canvas.drawBitmap(bitmapPicResize, 0, 0, paint);
canvas.save();

invalidate();
}

}