您的位置:首页 > 其它

自定义view画个圈圈

2016-01-31 17:19 453 查看
public class CircleImageView extends ImageView {

int bordercolor;

int borderwidth;

public CircleImageView(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

init(context,attrs);

}

private void init(Context context, AttributeSet attrs) {

// TODO Auto-generated method stub

TypedArray t=context.obtainStyledAttributes(attrs, R.styleable.CircleImageView);

bordercolor=t.getColor(R.styleable.CircleImageView_border_color, Color.RED);

borderwidth=t.getDimensionPixelSize(R.styleable.CircleImageView_border_width, 2);

t.recycle();

}

public CircleImageView(Context context, AttributeSet attrs) {

this(context, attrs,0);

}

public CircleImageView(Context context) {

this(context,null);

// TODO Auto-generated constructor stub

}

//将作为参数传入的方形的bitmap对象变成圆形的bitmap对象 然后画到组件上 传入的默认方形图片

public void setCircleImageBitmap(Bitmap bitmap){

int width=getWidth();

int height=getHeight();

if(width==0||height==0){

//手动指定width 和 height对应的大小

width=(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80, getResources().getDisplayMetrics());

height=(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 80, getResources().getDisplayMetrics());

}

bitmap=Bitmap.createScaledBitmap(bitmap, width, height, true);

Bitmap bm=Bitmap.createBitmap(width, height, bitmap.getConfig());

int r=Math.min(width, height)/2;

Canvas c=new Canvas(bm);

Paint p=new Paint(Paint.ANTI_ALIAS_FLAG);

p.setColor(Color.GREEN);

Shader shader=new BitmapShader(bitmap, TileMode.CLAMP, TileMode.CLAMP);

p.setShader(shader);

//p.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.SRC_IN));

//c.drawBitmap(bitmap, 0, 0, p);

c.drawCircle(width/2, height/2, r-borderwidth , p);

p.reset();

p.setStyle(Style.STROKE);

p.setAntiAlias(true);

p.setColor(bordercolor);

p.setStrokeWidth(borderwidth);

c.drawCircle(width/2, height/2, r-borderwidth, p);

setScaleType(ScaleType.CENTER);

super.setImageBitmap(bm);

}

}

<resources>

<declare-styleable name="CircleImageView">

<attr name="border_color" format="color"/>

<attr name="border_width" format="dimension"/>

</declare-styleable>

</resources>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: