1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
/** * 画个圆 * Created by cold on 15/9/21. */ public class BitShape extends View { private Bitmap bitmap; private Context context; private BitmapShader bitmapShader; //该view为50dp的圆 private int width=50; private int widthpx;//图片的宽度像素 private float mRadius;//圆半径 private Matrix mMatrix;//缩放矩阵 private Paint bitmapPaint;//画笔 //在构造方法中各种初始化 public BitShape(Context context) { super(context); this.context=context; //设置默认显示的图片 this.bitmap=getRes("default_pic"); bitmapPaint = new Paint(); bitmapPaint.setAntiAlias(true); mMatrix = new Matrix(); bitmapShader=new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); bitmapPaint.setShader(bitmapShader); } public BitShape(Context context, AttributeSet attrs) { super(context, attrs); this.context=context; this.bitmap=getRes("default_pic"); bitmapPaint = new Paint(); bitmapPaint.setAntiAlias(true); mMatrix = new Matrix(); bitmapShader=new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); bitmapPaint.setShader(bitmapShader); } //设置大小为50dp @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); widthpx=dp2px(width); mRadius=widthpx/2; setMeasuredDimension(widthpx,widthpx); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //先设置图片的缩放 float scale = 1.0f; // 拿到bitmap宽或高的小值 int bSize = Math.min(bitmap.getWidth(), bitmap.getHeight()); scale = widthpx * 1.0f / bSize; // shader的变换矩阵,我们这里主要用于放大或者缩小 mMatrix.setScale(scale, scale); // 设置变换矩阵 bitmapShader.setLocalMatrix(mMatrix); //调用.setShader方法 bitmapPaint.setShader(bitmapShader); //画圆 canvas.drawCircle(mRadius, mRadius, mRadius, bitmapPaint); } //改变要绘制的bitmap public void changeBitmap(Bitmap bitmap){ this.bitmap=bitmap; bitmapShader=new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); //通知重绘 postInvalidate(); } //获取Bitmap public Bitmap getRes(String name) { ApplicationInfo appInfo = context.getApplicationInfo(); int resID = getResources().getIdentifier(name, "drawable", appInfo.packageName); return BitmapFactory.decodeResource(getResources(), resID); } public int dp2px(int dpVal) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, getResources().getDisplayMetrics()); } } |
0 Comments