这几天因为项目需求,需要在ImageView上面叠加一层透明圆弧,并且在沿着圆弧的方向显示相应的文字,效果如下图所示:
拿到这个需求,首先想到的是自定义一个ImageView来实现此功能,即在onDraw()中绘制圆弧和文字。同时因为要保证圆弧的位置可以任意摆放,圆弧的颜色、透明度以及文字大小、颜色等都是可控的,所以增加了一些自定义属性。实现代码非常简单,如下:
1.自定义ImageView:
package com.linuxidc.customviewsdemo.views.ArcImageView;
import Android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.linuxidc.customviewsdemo.R;
/**
* Description:A custom ImageView with circular arc and text
* Author: XiaoYu
* Date: 2016/5/10 13:55
*/
public class ArcImageView extends ImageView {
/**
* The default text size.
*/
private final float DEFAULT_TEXT_SIZE = 20;
/**
* The default scale value which decides the width of arc.
*/
private final float DEFAULT_SCALE = 0.5f;
/**
* The default transparency of arc.
*/
private final int DEFAULT_ARC_ALPHA =100;
/**
* The default width of arc.
*/
private final int DEFAULT_ARC_WIDTH =160;
/**
* The default angle that the arc starts with.
*/
private final int DEFAULT_START_ANGLE = 180;
/**
* The default angle that the arc.
*/
private final int DEFAULT_SWEEP_ANGLE = 90;
/**
* The default distance along the path to add to the text's starting position.
*/
private final int DEFAULT_H_OFFSET = 100;
/**
* The default distance above(-) or below(+) the path to position the text.
*/
private final int DEFAULT_V_OFFSET = 20;
private Context mContext;
/**
* The text displayed on ImageView along arc.
*/
private String mDrawStr;
/**
* The font size of text.
*/
private float mTextSize = DEFAULT_TEXT_SIZE;
/**
* The scale value which decides the width of arc.
*/
private float mScale = DEFAULT_SCALE;
/**
* The transparency of arc.
*/
private int mArcAlpha = DEFAULT_ARC_ALPHA;
/**
* The width of arc.
*/
private int mArcWidth = DEFAULT_ARC_WIDTH;
/**
* The start angle of angle.
*/
private int mStartAngle = DEFAULT_START_ANGLE;
/**
* The swept angle of angle.
*/
private int mSweepAngle = DEFAULT_SWEEP_ANGLE;
/**
* The default distance along the path to add to the text's starting position.
*/
private float mHOffset = DEFAULT_H_OFFSET;
/**
* The default distance above(-) or below(+) the path to position the text.
*/
private float mVOffset = DEFAULT_V_OFFSET;
/**
* The style of arc, all styles includes LEFT_TOP, LEFT_BOTTOM, RIGHT_TOP, RIGHT_BOTTOM, CENTER。
* of course, you can add your own style according to your demands.
*/
private int mDrawStyle;
/**
* The color of arc.
*/
private int mArcColor;
/**
* The color of text.
*/
private int mTextColor;
public ArcImageView(Context context) {
super(context);
this.mContext = context;
}
public ArcImageView(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
obtainAttributes(attrs);
}