然后我们接着看onDraw()方法:
- @Override
- protected void onDraw(Canvas canvas) {
- super.onDraw(canvas);
- if (itemsLayout == null) {
- if (itemsWidth == 0) {
- calculateLayoutWidth(getWidth(), MeasureSpec.EXACTLY);
- } else {
- createLayouts(itemsWidth, labelWidth);
- }
- }
- if (itemsWidth > 0) {
- canvas.save();
- // Skip padding space and hide a part of top and bottom items
- canvas.translate(PADDING, -ITEM_OFFSET);
- drawItems(canvas);
- drawValue(canvas);
- canvas.restore();
- }
- drawCenterRect(canvas);
- drawShadows(canvas);
- }
在onDraw方法中,也调用了CreateLayout()方法,然后在后面调用drawCenterRect()、drawItems()、drawValue()、绘制阴影drawShadows()两个方法:
- /**
- * Draws shadows on top and bottom of control
- * @param canvas the canvas for drawing
- */
- private void drawShadows(Canvas canvas) {
- topShadow.setBounds(0, 0, getWidth(), getHeight() / visibleItems);
- topShadow.draw(canvas);
- bottomShadow.setBounds(0, getHeight() - getHeight() / visibleItems,
- getWidth(), getHeight());
- bottomShadow.draw(canvas);
- }
- /**
- * Draws value and label layout
- * @param canvas the canvas for drawing
- */
- private void drawValue(Canvas canvas) {
- valuePaint.setColor(VALUE_TEXT_COLOR);
- valuePaint.drawableState = getDrawableState();
- Rect bounds = new Rect();
- itemsLayout.getLineBounds(visibleItems / 2, bounds);
- // draw label
- if (labelLayout != null) {
- canvas.save();
- canvas.translate(itemsLayout.getWidth() + LABEL_OFFSET, bounds.top);
- labelLayout.draw(canvas);
- canvas.restore();
- }
- // draw current value
- if (valueLayout != null) {
- canvas.save();
- canvas.translate(0, bounds.top + scrollingOffset);
- valueLayout.draw(canvas);
- canvas.restore();
- }
- }
- /**
- * Draws items
- * @param canvas the canvas for drawing
- */
- private void drawItems(Canvas canvas) {
- canvas.save();
- int top = itemsLayout.getLineTop(1);
- canvas.translate(0, - top + scrollingOffset);
- itemsPaint.setColor(ITEMS_TEXT_COLOR);
- itemsPaint.drawableState = getDrawableState();
- itemsLayout.draw(canvas);
- canvas.restore();
- }
- /**
- * Draws rect for current value
- * @param canvas the canvas for drawing
- */
- private void drawCenterRect(Canvas canvas) {
- int center = getHeight() / 2;
- int offset = getItemHeight() / 2;
- centerDrawable.setBounds(0, center - offset, getWidth(), center + offset);
- centerDrawable.draw(canvas);
- }
