按比例劃線的工具類

目標:一個view,按照給定的比例畫不同顏色的線段充滿整個view

方法:

public class SegmentLineView extends View {
	private Paint paint;
	private LineItem[] lines;
	public SegmentLineView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init();
	}

	public SegmentLineView(Context context) {
		super(context);
		init();
	}

	public SegmentLineView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}
	private void init() {
		paint = new Paint();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		if (lines==null || lines.length==0) {
			return;
		}
		int allweight = 0;
		for (int i = 0; i < lines.length; i++) {
			allweight += lines[i].getWeight();
		}
		float width = getWidth();
		float cwidth = 0.0f;
		for (int i = 0; i < lines.length; i++) {
			LineItem lineItem = lines[i];
			paint.setColor(lineItem.getColor());
			canvas.drawRect(cwidth, 0, cwidth+width*(lineItem.getWeight()/(allweight*1.0f)), getHeight(), paint);
			cwidth += width*(lineItem.getWeight()/(allweight*1.0f));
		}
	}
	
	public LineItem[] getLines() {
		return lines;
	}

	public void setLines(LineItem[] lines) {
		this.lines = lines;
		invalidate();
	}
	
	public static class LineItem{
		private int weight;
		private int Color;
		
		public LineItem(int weight, int color) {
			super();
			this.weight = weight;
			Color = color;
		}
		public int getWeight() {
			return weight;
		}
		public void setWeight(int weight) {
			this.weight = weight;
		}
		public int getColor() {
			return Color;
		}
		public void setColor(int color) {
			Color = color;
		}
		@Override
		public String toString() {
			return "LineItem [weight=" + weight + ", Color=" + Color + "]";
		}
	}
}

具體使用方法http://blog.csdn.net/zwx622/article/details/37693387

效果:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章