源代码及可执行文件下载地址:http://files.cnblogs.com/rainboy2010/CircleViewDemo.zip

CircleView-LMLPHP

自定义View控件实现圆形的背景+居中的文字,主要代码如下:

public class CircleView extends View
{ private static final int DEFAULT_DRAW_COLOR = Color.BLACK;
private static final int DEFAULT_TEXT_COLOR=Color.WHITE;
private static final int DEFAULT_TEXT_SIZE=30;
private static final String DEFAULT_TEXT="";
private int mDrawColor=DEFAULT_DRAW_COLOR;
private int mTextColor=DEFAULT_TEXT_COLOR;
private int mTextSize=DEFAULT_TEXT_SIZE;
private String mText=DEFAULT_TEXT; private final RectF mDrawableRect = new RectF();
private final Paint mDrawPaint = new Paint();
private final Paint mTextPaint = new Paint(); public CircleView(Context context)
{
super(context);
init();
} public CircleView(android.content.Context context, android.util.AttributeSet attrs)
{
this(context,attrs,0);
}
public CircleView(android.content.Context context, android.util.AttributeSet attrs, int defStyleAttr)
{
super(context,attrs,defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView,defStyleAttr,0); mDrawColor=a.getColor(R.styleable.CircleView_draw_color, DEFAULT_DRAW_COLOR);
mTextColor=a.getColor(R.styleable.CircleView_text_color, DEFAULT_TEXT_COLOR);
mTextSize=a.getDimensionPixelSize(R.styleable.CircleView_text_size, DEFAULT_TEXT_SIZE);
mText=a.getString(R.styleable.CircleView_text); a.recycle(); init();
}
private void init()
{
mDrawPaint.setStyle(Paint.Style.FILL);
mDrawPaint.setColor(mDrawColor);
mTextPaint.setColor(mTextColor);
mTextPaint.setTextSize(mTextSize);
mTextPaint.setTextAlign(Align.CENTER);
} public void setDrawColor(int drawColor)
{
if(drawColor==mDrawColor)
{
return;
}
mDrawColor = drawColor;
mDrawPaint.setColor(mDrawColor);
invalidate();
}
public int getDrawColor()
{
return mDrawColor;
} public void setTextColor(int textColor)
{
if(textColor==mTextColor)
{
return;
}
mTextColor = textColor;
mTextPaint.setColor(mTextColor);
invalidate();
}
public int getTextColor()
{
return mTextColor; } public void setTextSize(int textSize)
{
if(textSize==mTextSize)
{
return;
}
mTextSize = textSize;
mTextPaint.setTextSize(mTextSize);
invalidate();
}
public int getTextSize()
{
return mTextSize;
} public void setText(String text)
{
if(text.equals(mText))
{
return;
}
mText = text;
invalidate();
}
public String getText()
{
return mText;
} @Override
protected void onDraw(Canvas canvas)
{
mDrawableRect.set(0, 0, getWidth(), getHeight());
canvas.drawCircle(mDrawableRect.centerX(),mDrawableRect.centerY(),mDrawableRect.width()/2, mDrawPaint); if(!mText.equals(""))
{
FontMetrics fontMetrics =mTextPaint.getFontMetrics();
float fontHeight = fontMetrics.bottom - fontMetrics.top;//获取字体高度
float textBaseY = mDrawableRect.height()/2+fontHeight/2 - fontMetrics.bottom;//获取BaseLine
canvas.drawText(mText, mDrawableRect.centerX(), textBaseY, mTextPaint);//水平垂直居中
}
super.onDraw(canvas);
}
}

  

04-28 03:41