本文主要是介绍按比例划线的工具类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目标:一个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();}@Overrideprotected 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;}@Overridepublic String toString() {return "LineItem [weight=" + weight + ", Color=" + Color + "]";}}
}
具体使用方法 http://blog.csdn.net/zwx622/article/details/37693387
效果:
这篇关于按比例划线的工具类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!