目标:一个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) {Draw(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.Color());canvas.drawRect(cwidth, 0, cwidth+width*(Weight()/(allweight*1.0f)), getHeight(), paint);cwidth += width*(Weight()/(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 + "]";}}
}
效果:
本文发布于:2024-01-27 22:49:30,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17063669713118.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |