画圆遇到的问题:图片单位不一样,导致图片只能显示出圆的一部分;看代码:
public class MyCircleIamge extends ImageView { private Context context;
private Paint paint;
private Canvas mcan;
private Bitmap mbit; public MyCircleIamge(Context context) {
super(context,null);
} public MyCircleIamge(Context context, AttributeSet attrs) {
super(context, attrs); this.context = context;
paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
paint.setDither(true);
paint.setColor(Color.RED); }
@Override
protected void onDraw(Canvas canvas) {
// super.onDraw(canvas);
Drawable drawable = getDrawable();
if (null != drawable){
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
int cy = bitmap.getHeight()/2;
int cx = bitmap.getWidth()/2;
int radius = (cx>cy?cy:cx); mbit = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
mcan = new Canvas(mbit); mcan.drawCircle(cx,cy,radius,paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); Rect src1 = new Rect(0,0,bitmap.getWidth(),bitmap.getHeight());
mcan.drawBitmap(bitmap,src1,src1,paint);
paint.reset(); Rect src = new Rect(0,0,mbit.getWidth(),mbit.getHeight());
Rect dst = new Rect(0,0,getWidth(),getHeight());
canvas.drawBitmap(mbit,src,dst,paint); }else {
super.onDraw(canvas);
}
}
这样一运行的结果:
现在改动代码:
看效果:
xml布局:
刚开始的时,我总想不通,后来才发现原来画布的大小是不一样的:bitmap.getWidth() = 1125(px)
而getWidth()=300dp=469(px)相差是很大的,新建的画布的大小一定得和原来的bitmap的大小是一样的。图片的大小和控件的大小不一样的(控件的宽大小为:469px,图片的宽大小为:1125px),我们应该以图片的大小为准。
后面同样如此,如果你画的图片和我一样的话:请检查一下这几个地方:
//px转换成dp
public static int px2dp(Context context,float pxValue){
final float scale = context.getResources().getDisplayMetrics().densityDpi;
return (int)((pxValue*160)/scale+0.5f);
}