仿墨跡24小時天氣自定義View

語言: CN / TW / HK

先看墨跡天氣效果圖

5506445253_63249103744_1656936370197_694x449.gif

因為需求原因,改了一些樣式

5506445253_63339371021_1657021325668_687x425.gif

話不多說,直接開始,首先是畫出這條曲線,找到每個小時溫度對應點位,連成一條線,左邊顯示最高溫度和最低溫度,最高溫度對應曲線中的最高點,最低溫度對應曲線中的最低點,直接上程式碼 java private Point calculateTempPoint(int left, int right, int temp) { double minHeight = tempBaseTop; double maxHeight = tempBaseBottom; double tempY = maxHeight - (temp - minTemp) * 1.0 / (maxTemp - minTemp) * (maxHeight - minHeight); Point point = new Point((left + right) / 2, (int) tempY); return point; } 傳入點的左邊距,右邊距和這個時間段對應的溫度,返回一個Point類,Point類中有x,y兩個屬性,構造方法如下 java public Point(int x, int y) { this.x = x; this.y = y; } tempBaseTop和tempBaseBottom是在初始化中按高度比例來分 java tempBaseTop = (mHeight - bottomTextHeight) / 3; tempBaseBottom = (mHeight - bottomTextHeight) * 3 / 4; bottomTextHeight是下方數字文字高度\ 獲取每個溫度對應的座標軸之前,先拿到24小時天氣資料中的最高溫和最低溫,這樣就能確定每個點位的距離y軸的座標。拿到24個座標點後,直接來第一步,畫出曲線,直接上程式碼 ```java Path path = new Path(); Point point0 = listItems.get(0).getTempPoint(); path.moveTo(point0.x, point0.y);

for (int i = 0; i < listItems.size(); i++) { Point point = listItems.get(i).getTempPoint(); if (i != 0) { Point pointPre = listItems.get(i - 1).getTempPoint(); if (i == 1) { path.lineTo(point.x, point.y); } else { path.rLineTo(point.x - pointPre.x, point.y - pointPre.y); } } } canvas.drawPath(path, linePaint); ``` 直接new一個Path,使用moveTo方法移動到第一個點位,然後直接for迴圈,第一個點不畫,從1開始,直接lineTo到指定的x,y座標,這裡第一條線使用了lineTo,後面都是用的rLineTo,也就是從上一條線的最終點開始畫,就不需要頻繁的moveTo了。本來打算使用三階貝塞爾曲線畫的,畫出來之後發現每條線的連線處有很明顯的折角,不平滑,可能是我用的方法不對,有明白的可以跟我說說,三階貝塞爾畫出來的就像下面這樣

5506445253_63262601417_IMG_20220705_085830.jpg 再看下使用畫直線的方式畫出來的效果

5506445253_63264419320_IMG_20220705_091358.jpg 看的出來,這不是差不多嘛,就是更直了一點,這不是玩呢,別急,還差一步,給Paint設定PathEffect,程式碼如下 java PathEffect pathEffect = new CornerPathEffect(180); linePaint.setPathEffect(pathEffect); CornerPathEffect的作用是通過將線段之間的任何銳角替換為指定半徑的圓角來轉換繪製的幾何圖形(STROKE 或 FILL 樣式)。引數:半徑 - 線段之間的圓角

5506445253_63268350797_IMG_20220705_094126.jpg 是不是平滑了很多。\ 曲線結束之後先畫出每個天氣icon所在的矩形框,每個矩形框之間都有一定的縫隙,直接上程式碼 ```java Point point0 = listItems.get(0).tempPoint; Path pathBG = new Path(); pathBG.moveTo(point0.x, point0.y); for (int i = 0; i < listItems.size(); i++) { Point point = listItems.get(i).getTempPoint(); if (i != 0) { Point pointPre = listItems.get(i - 1).getTempPoint(); if (i == 1) { pathBG.lineTo(point.x, point.y); } else { if (listItems.get(i).getIcon() != -1) pathBG.rLineTo(point.x - pointPre.x - DisplayUtil.dip2px(getContext(), 1), point.y - pointPre.y); else pathBG.rLineTo(point.x - pointPre.x, point.y - pointPre.y); }

    Point pointBackup = listItems.get(0).getTempPoint();
    if (listItems.get(i).getIcon() != -1 || (getGoneBehind(i) && i == listItems.size() - 1)) {
        for (int j = 0; j < i; j++) {
            if (listItems.get(j).getIcon() != -1) {
                pointBackup = listItems.get(j).getTempPoint();
            }
        }
        if (listItems.get(i).getTempPoint() != pointBackup) {
            int height = mHeight - bottomTextHeight - DisplayUtil.dip2px(getContext(), 4) - point.y;
            pathBG.rLineTo(0, height);
            pathBG.rLineTo(pointBackup.x - point.x + DisplayUtil.dip2px(getContext(), 1), 0);
            canvas.drawPath(pathBG, rectPaint);
            pathBG.reset();
            //移到新的點開始畫
            pathBG.moveTo(point.x, point.y);
        }
    }
}

} java private boolean getGoneBehind(int index) { List data = new ArrayList<>(); for (int k = index; k < listItems.size(); k++) { data.add(listItems.get(k).res == -1); } return !data.contains(false); } 這裡前面和畫曲線一樣,原理就是先畫出一個天氣icon所在的矩形框上方的曲線,然後從曲線的末端向下畫一條直線,在向左畫至矩形框的左邊界,然後封閉起來。可以看到這裡面有很多getIcon() != -1的判斷,這些是在塞資料的時候判斷當前時間段的icon是否和上一個一樣,一樣的話就把icon替換成-1,程式碼如下java int icon = list.get(0).getIcon(); for (int i = 0; i < list.size(); i++) { if (i != 0 && icon == list.get(i).getIcon()) { list.get(i).setIcon(-1); } else { icon = list.get(i).getIcon(); } } ```

由於每個矩形中間需要間隙,就在頂部和底部的線時減去了1dp,程式碼中可以看到除了畫曲線外只畫了兩條線,但是卻實現了填充矩形的效果,這個是因為我給rectPaint設定了Style時傳入的屬性是Paint.Style.FILL,設定FILL屬性後,三角形只需要畫出兩條線就可自動封閉,矩形畫出三條線,如果不方便使用FILL屬性的話,可以使用Path提供的方法,path.close();,效果等同於FILL,封閉矩形後使用path.reset();清除路徑中的所有線條和曲線,然後移動到下一個開始畫曲線的點,迴圈下去,看一下效果

5506445253_63317592872_IMG_20220705_162537.jpg 矩形結束之後就是天氣icon了。在看一下墨跡天氣的效果圖 5506445253_63249103744_1656936370197_694x449.gif

從圖中可以看到,天氣的icon是在每個矩形的正中間,隨著手指的滑動,最左邊的icon所在的矩形如果被view的左邊界蓋住,矩形中的icon保持在view的左邊界和矩形的右邊界中間,最右邊同理。程式碼如下 java for (int i = 0; i < listItems.size(); i++) { Point point = listItems.get(i).getTempPoint(); if (i != 0) { Point pointBackup = listItems.get(0).getTempPoint(); if (listItems.get(i).getIcon() != -1 || (getGoneBehind(i) && i == listItems.size() - 1)) { int icon = -1; int indexBackUp = 0; for (int j = 0; j < i; j++) { if (listItems.get(j).getIcon() != -1) { icon = listItems.get(j).getIcon(); indexBackUp = j; pointBackup = listItems.get(j).getTempPoint(); } } if (listItems.get(i).getTempPoint() != pointBackup) { int left = (point.x - pointBackup.x) / 2 + pointBackup.x - DisplayUtil.dip2px(getContext(), 10); int right = (point.x - pointBackup.x) / 2 + pointBackup.x + DisplayUtil.dip2px(getContext(), 10); int newLeft = (point.x - (pointBackup.x - getItemLeftMargin(indexBackUp))) / 2 + (pointBackup.x - getItemLeftMargin(indexBackUp)); int newRight = ((point.x + getItemRightMargin(i)) - pointBackup.x) / 2 + pointBackup.x; if (getItemLeftMargin(indexBackUp) < 0 && newLeft + DisplayUtil.dip2px(getContext(), 20) < point.x && i - indexBackUp > 1) { left = newLeft - DisplayUtil.dip2px(getContext(), 10); right = left + DisplayUtil.dip2px(getContext(), 20); } else if (getItemLeftMargin(indexBackUp) < 0 && newLeft + DisplayUtil.dip2px(getContext(), 40) >= point.x && i - indexBackUp > 1) { left = point.x - DisplayUtil.dip2px(getContext(), 30); right = left + DisplayUtil.dip2px(getContext(), 20); } if (getItemRightMargin(i) < 0 && newRight > pointBackup.x + DisplayUtil.dip2px(getContext(), 10) && i - indexBackUp > 1) { right = newRight + DisplayUtil.dip2px(getContext(), 10); left = right - DisplayUtil.dip2px(getContext(), 20); } if (getItemLeftMargin(indexBackUp) < 0 && getItemRightMargin(i) < 0) { left = pointBackup.x - getItemLeftMargin(indexBackUp) + scrollWidth / 2 - DisplayUtil.dip2px(getContext(), 10); right = left + DisplayUtil.dip2px(getContext(), 20); } Drawable drawable = ContextCompat.getDrawable(getContext(), icon); drawable.setBounds(left, tempBaseBottom + DisplayUtil.dip2px(getContext(), 5), right, tempBaseBottom + DisplayUtil.dip2px(getContext(), 25)); drawable.draw(canvas); } } } } 首先就是拿到icon所在矩形上方曲線的起始點,記住起始點的下標,x,y和icon,icon所在矩形上方曲線結束點的x軸座標減去icon所在矩形上方曲線起始點的x軸座標就可以拿到這個矩形的寬,寬除2在加上icon所在矩形上方曲線結束點的x軸座標就是矩形中間點距離左邊的邊距,預設icon的left和right是在中間點的基礎上減去10dp和加上10dp。\ 然後就是判斷當前icon所在的矩形左邊界或者右邊界是否超出view的邊界,因為newLeft是隨著手指滑動不斷減小或者增加的,所以需要滿足當前icon所在矩形的左邊界超出view的邊界,且左邊界不能超過右邊界,右邊同理,需要注意的是,當前icon的矩形如果只佔了一格,就不需要改變邊界,一直保持在矩形的中間就好。除了這兩種情況外還有一種情況,就是矩形兩邊都超出view的邊界,這時就是讓天氣icon保持在view的正中間就好了。\ 那麼如何拿到當前icon所在矩形上方曲線起始點距離view左邊界的距離呢,程式碼如下 ```java / * 點距離左邊的位置 * @param i * @return
/ private int getItemLeftMargin(int i) { int left = MARGIN_LEFT_ITEM + i * ITEM_WIDTH + ITEM_WIDTH / 2; return left - scrollOffset; }

/ * 點距離右邊的位置 * @param i * @return / private int getItemRightMargin(int i) { int left = MARGIN_LEFT_ITEM + i * ITEM_WIDTH + ITEM_WIDTH / 2; return scrollWidth - (left - scrollOffset); } MARGIN_LEFT_ITEM:左邊預留寬度\ ITEM_WIDTH:每個Item的寬度\ scrollOffset:滾動偏移量\ scrollWidth:HorizontalScrollView的寬度\ 左邊界距離螢幕左邊的編輯就是當前icon所在矩形上方曲線起始點的x軸減去滑動的偏移量,右邊界距離右邊就是HorizontalScrollView的寬度減去距離螢幕左邊界的值\ 24小時天氣自定義view是被另一個自定義View中包含的,它繼承於HorizontalScrollView,需要修改的程式碼如下java @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int offset = computeHorizontalScrollOffset(); int maxOffset = computeHorizontalScrollRange() - DisplayUtil.getScreenWidth(getContext()); if (today24HourView != null) { today24HourView.setScrollOffset(offset, maxOffset, getWidth()); } }

public void setToday24HourView(Today24HourView today24HourView) {
    this.today24HourView = today24HourView;
    invalidate();
}

computeHorizontalScrollOffset()計算水平滾動條拇指在水平範圍內的水平偏移量\ computeHorizontalScrollRange()滾動檢視的滾動範圍是其所有子檢視的總寬度java //設定scrollerView的滾動條的位置,通過位置計算當前的時段 public void setScrollOffset(int offset, int maxScrollOffset, int scrollWidth) { this.maxScrollOffset = maxScrollOffset; this.scrollWidth = scrollWidth; scrollOffset = offset; currentItemIndex = calculateItemIndex(offset); invalidate(); } maxScrollOffset:最大滾動距離\ scrollWidth:HorizontalScrollView的寬度\ scrollOffset:滾動偏移量\ xml中程式碼如下xml ```

5506445253_63324907904_1657012359644_687x218.gif 接下來就是當前天氣指標了,就是根據手指滑動,向左或向右偏移,並且滑動到不同的item,改變指標中的內容,程式碼如下 java WeatherHoursModel item = listItems.get(i); if (currentItemIndex == i) { int Y = getTempBarY(); Rect targetRect = new Rect( getScrollBarX(), Y - DisplayUtil.dip2px(getContext(), 40), getScrollBarX() + DisplayUtil.dip2px(getContext(), 92), Y - DisplayUtil.dip2px(getContext(), 14)); Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.bg_indicator_text); drawable.setBounds(targetRect); drawable.draw(canvas); //畫出溫度提示 Paint.FontMetricsInt fontMetrics = textPaint.getFontMetricsInt(); int baseline = (targetRect.bottom + targetRect.top - fontMetrics.bottom - fontMetrics.top) / 2; textPaint.setTextAlign(Paint.Align.CENTER); textPaint.setTextSize(DisplayUtil.sp2px(getContext(), 10)); canvas.drawText(TimeUtils.getDateHHmm(item.getTempStamp()) + " " + item.getWeather() + " " + item.getTemperature() + "°", targetRect.centerX(), baseline, textPaint); int height = mHeight - bottomTextHeight - DisplayUtil.dip2px(getContext(), 4); canvas.drawLine(targetRect.centerX(), targetRect.bottom + DisplayUtil.dip2px(getContext(), 4), targetRect.centerX(), height, indicatorLinePaint); } java //計算溫度提示文字的運動軌跡 private int getTempBarY() { int x = getScrollBarX(); int sum = MARGIN_LEFT_ITEM; Point startPoint = null, endPoint; int i; for (i = 0; i < ITEM_SIZE; i++) { sum += ITEM_WIDTH; if (x < sum) { startPoint = listItems.get(i).getTempPoint(); break; } } if (i + 1 >= ITEM_SIZE || startPoint == null) return listItems.get(ITEM_SIZE - 1).getTempPoint().y; endPoint = listItems.get(i + 1).getTempPoint(); int left = MARGIN_LEFT_ITEM + i * ITEM_WIDTH; int y = (int) (startPoint.y + (x - left) * 1.0 / ITEM_WIDTH * (endPoint.y - startPoint.y)); return y; } java private int getScrollBarX() { int x = (ITEM_SIZE - 5) * ITEM_WIDTH * scrollOffset / maxScrollOffset; x = x + MARGIN_LEFT_ITEM; return x; } 5506445253_63340840294_1657023135269_687x228.gif

然後就是實現當前選中矩形改變顏色,這個很簡單,程式碼如下 java if (pointBackup.x < getScrollBarX() + DisplayUtil.dip2px(getContext(), 46) && getScrollBarX() + DisplayUtil.dip2px(getContext(), 46) < point.x) { rectPaint.setColor(Color.parseColor("#33FFFFFF")); } else { rectPaint.setColor(Color.parseColor("#1AFFFFFF")); } 至於下面的時間欄位,和左面的最高溫和最低溫就不寫了,很簡單,計算一下位置就行,有興趣的複製下面完整程式碼自己看看就行\ 下面是完整程式碼\ Today24HourView.java ```java public class Today24HourView extends View { private static final String TAG = "Today24HourView"; private static final int ITEM_SIZE = 24; //24小時 private int ITEM_WIDTH; //每個Item的寬度 private int MARGIN_LEFT_ITEM; //左邊預留寬度 private int MARGIN_RIGHT_ITEM; //右邊預留寬度 private int bottomTextHeight; private int scrollWidth;

private int mHeight, mWidth;
private int tempBaseTop;  //溫度折線的上邊Y座標
private int tempBaseBottom; //溫度折線的下邊Y座標
private Paint bitmapPaint, linePaint, rectPaint, indicatorLinePaint;
private TextPaint textPaint;

private List<WeatherHoursModel> listItems;
private int maxScrollOffset = 0;//滾動條最長滾動距離
private int scrollOffset = 0; //滾動條偏移量
private int currentItemIndex = 0; //當前滾動的位置所對應的item下標

private int maxTemp;
private int minTemp;

public Today24HourView(Context context) {
    this(context, null);
}

public Today24HourView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public Today24HourView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init() {
    MARGIN_LEFT_ITEM = DisplayUtil.dip2px(getContext(), 2);
    MARGIN_RIGHT_ITEM = DisplayUtil.dip2px(getContext(), 20);
    ITEM_WIDTH = DisplayUtil.dip2px(getContext(), 30);
    bottomTextHeight = DisplayUtil.dip2px(getContext(), 16);
    mWidth = MARGIN_LEFT_ITEM + MARGIN_RIGHT_ITEM + ITEM_SIZE * ITEM_WIDTH;
    mHeight = DisplayUtil.dip2px(getContext(), 140);
    tempBaseTop = (mHeight - bottomTextHeight) / 3;
    tempBaseBottom = (mHeight - bottomTextHeight) * 3 / 4;
    listItems = new ArrayList<>();
    initPaint();
}

private void initPaint() {

    rectPaint = new Paint();
    rectPaint.setColor(Color.parseColor("#1AFFFFFF"));
    rectPaint.setAntiAlias(true);
    rectPaint.setStyle(Paint.Style.FILL);
    rectPaint.setStrokeCap(Paint.Cap.ROUND);
    rectPaint.setStrokeJoin(Paint.Join.ROUND);
    rectPaint.setStrokeWidth(1);

    PathEffect pathEffect = new CornerPathEffect(180);
    linePaint = new Paint();
    linePaint.setColor(Color.WHITE);
    linePaint.setPathEffect(pathEffect);
    linePaint.setAntiAlias(true);
    linePaint.setStrokeCap(Paint.Cap.ROUND);
    linePaint.setStrokeJoin(Paint.Join.ROUND);
    linePaint.setStyle(Paint.Style.STROKE);
    linePaint.setStrokeWidth(10);

    textPaint = new TextPaint();
    textPaint.setColor(Color.WHITE);
    textPaint.setAntiAlias(true);

    bitmapPaint = new Paint();
    bitmapPaint.setAntiAlias(true);

    indicatorLinePaint = new Paint();
    indicatorLinePaint = new Paint();
    indicatorLinePaint.setColor(Color.WHITE);
    indicatorLinePaint.setAntiAlias(true);
    indicatorLinePaint.setStrokeCap(Paint.Cap.ROUND);
    indicatorLinePaint.setStyle(Paint.Style.STROKE);
    indicatorLinePaint.setStrokeWidth(2);
}

public void setHourItems(List<WeatherHoursModel> listItems) {
    this.listItems.clear();
    List<WeatherHoursModel> list = new ArrayList<>(listItems);
    maxTemp = list.get(0).getTemperature();
    minTemp = list.get(0).getTemperature();
    for (WeatherHoursModel listItem : list) {
        if (listItem.getTemperature() > maxTemp)
            maxTemp = listItem.getTemperature();
        if (listItem.getTemperature() < minTemp)
            minTemp = listItem.getTemperature();
    }
    int icon = list.get(0).getIcon();
    for (int i = 0; i < list.size(); i++) {
        int left = MARGIN_LEFT_ITEM + i * ITEM_WIDTH;
        int right = left + ITEM_WIDTH;
        Point point = calculateTempPoint(left, right, list.get(i).getTemperature());
        if (i != 0 && icon == list.get(i).getIcon()) {
            list.get(i).setIcon(-1);
        } else {
            icon = list.get(i).getIcon();
        }
        list.get(i).setTempPoint(point);
    }
    this.listItems.addAll(list);
    invalidate();
}

private Point calculateTempPoint(int left, int right, int temp) {
    double minHeight = tempBaseTop;
    double maxHeight = tempBaseBottom;
    double tempY = maxHeight - (temp - minTemp) * 1.0 / (maxTemp - minTemp) * (maxHeight - minHeight);
    Point point = new Point((left + right) / 2, (int) tempY);
    return point;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    setMeasuredDimension(mWidth, mHeight);
}

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    onDrawLine(canvas);

// drawLeftTempText(canvas); for (int i = 0; i < listItems.size(); i++) { onDrawTemp(canvas, i); onDrawText(canvas, i); } }

private void onDrawTemp(Canvas canvas, int i) {
    WeatherHoursModel item = listItems.get(i);
    if (currentItemIndex == i) {
        int Y = getTempBarY();
        Rect targetRect = new Rect(
                getScrollBarX(),
                Y - DisplayUtil.dip2px(getContext(), 40),
                getScrollBarX() + DisplayUtil.dip2px(getContext(), 92),
                Y - DisplayUtil.dip2px(getContext(), 14));
        Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.bg_indicator_text);
        drawable.setBounds(targetRect);
        drawable.draw(canvas);
        //畫出溫度提示
        Paint.FontMetricsInt fontMetrics = textPaint.getFontMetricsInt();
        int baseline = (targetRect.bottom + targetRect.top - fontMetrics.bottom - fontMetrics.top) / 2;
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setTextSize(DisplayUtil.sp2px(getContext(), 10));
        canvas.drawText(TimeUtils.getDateHHmm(item.getTempStamp()) + " " + item.getWeather() + "  " + item.getTemperature() + "°", targetRect.centerX(), baseline, textPaint);
        int height = mHeight - bottomTextHeight - DisplayUtil.dip2px(getContext(), 4);
        canvas.drawLine(targetRect.centerX(), targetRect.bottom + DisplayUtil.dip2px(getContext(), 4), targetRect.centerX(), height, indicatorLinePaint);
    }
}

/**
 * 溫度的折線,為了折線比較平滑,做了貝塞爾曲線
 * 畫了貝塞爾曲線後一點都不平滑,放棄
 * 直接使用直線連線起來,用CornerPathEffect改變連線處的弧度,順滑無比
 *
 * @param canvas
 */
private void onDrawLine(Canvas canvas) {
    if (listItems.size() > 0) {
        Path path = new Path();
        Point point0 = listItems.get(0).getTempPoint();
        path.moveTo(point0.x, point0.y);
        Path pathBG = new Path();
        pathBG.moveTo(point0.x, point0.y);

        for (int i = 0; i < listItems.size(); i++) {
            Point point = listItems.get(i).getTempPoint();
            if (i != 0) {
                Point pointPre = listItems.get(i - 1).getTempPoint();
                if (i == 1) {
                    path.lineTo(point.x, point.y);
                    pathBG.lineTo(point.x, point.y);
                } else {
                    path.rLineTo(point.x - pointPre.x, point.y - pointPre.y);
                    if (listItems.get(i).getIcon() != -1)
                        pathBG.rLineTo(point.x - pointPre.x - DisplayUtil.dip2px(getContext(), 1), point.y - pointPre.y);
                    else
                        pathBG.rLineTo(point.x - pointPre.x, point.y - pointPre.y);
                }

                Point pointBackup = listItems.get(0).getTempPoint();
                if (listItems.get(i).getIcon() != -1 || (getGoneBehind(i) && i == listItems.size() - 1)) {
                    int icon = -1;
                    int indexBackUp = 0;
                    for (int j = 0; j < i; j++) {
                        if (listItems.get(j).getIcon() != -1) {
                            icon = listItems.get(j).getIcon();
                            indexBackUp = j;
                            pointBackup = listItems.get(j).getTempPoint();
                        }
                    }
                    if (pointBackup.x < getScrollBarX() + DisplayUtil.dip2px(getContext(), 46) && getScrollBarX() + DisplayUtil.dip2px(getContext(), 46) < point.x) {
                        rectPaint.setColor(Color.parseColor("#33FFFFFF"));
                    } else {
                        rectPaint.setColor(Color.parseColor("#1AFFFFFF"));
                    }
                    if (listItems.get(i).getTempPoint() != pointBackup) {
                        int height = mHeight - bottomTextHeight - DisplayUtil.dip2px(getContext(), 4) - point.y;
                        pathBG.rLineTo(0, height);
                        pathBG.rLineTo(pointBackup.x - point.x + DisplayUtil.dip2px(getContext(), 1), 0);
                        canvas.drawPath(pathBG, rectPaint);
                        pathBG.reset();
                        //移到新的點開始畫
                        pathBG.moveTo(point.x, point.y);

                        int left = (point.x - pointBackup.x) / 2 + pointBackup.x - DisplayUtil.dip2px(getContext(), 10);
                        int right = (point.x - pointBackup.x) / 2 + pointBackup.x + DisplayUtil.dip2px(getContext(), 10);
                        int newLeft = (point.x - (pointBackup.x - getItemLeftMargin(indexBackUp))) / 2 + (pointBackup.x - getItemLeftMargin(indexBackUp));
                        int newRight = ((point.x + getItemRightMargin(i)) - pointBackup.x) / 2 + pointBackup.x;
                        if (getItemLeftMargin(indexBackUp) < 0 && newLeft + DisplayUtil.dip2px(getContext(), 20) < point.x && i - indexBackUp > 1) {
                            left = newLeft - DisplayUtil.dip2px(getContext(), 10);
                            right = left + DisplayUtil.dip2px(getContext(), 20);
                        } else if (getItemLeftMargin(indexBackUp) < 0 && newLeft + DisplayUtil.dip2px(getContext(), 40) >= point.x && i - indexBackUp > 1) {
                            left = point.x - DisplayUtil.dip2px(getContext(), 30);
                            right = left + DisplayUtil.dip2px(getContext(), 20);
                        }
                        if (getItemRightMargin(i) < 0 && newRight > pointBackup.x + DisplayUtil.dip2px(getContext(), 10) && i - indexBackUp > 1) {
                            right = newRight + DisplayUtil.dip2px(getContext(), 10);
                            left = right - DisplayUtil.dip2px(getContext(), 20);
                        }
                        if (getItemLeftMargin(indexBackUp) < 0 && getItemRightMargin(i) < 0) {
                            left = pointBackup.x - getItemLeftMargin(indexBackUp) + scrollWidth / 2 - DisplayUtil.dip2px(getContext(), 10);
                            right = left + DisplayUtil.dip2px(getContext(), 20);
                        }
                        Drawable drawable = ContextCompat.getDrawable(getContext(), icon);
                        drawable.setBounds(left,
                                tempBaseBottom + DisplayUtil.dip2px(getContext(), 5),
                                right,
                                tempBaseBottom + DisplayUtil.dip2px(getContext(), 25));
                        drawable.draw(canvas);
                    }
                }
            }
        }
        canvas.drawPath(path, linePaint);
    }
}

private boolean getGoneBehind(int index) {
    List<Boolean> data = new ArrayList<>();
    for (int k = index; k < listItems.size(); k++) {
        data.add(listItems.get(k).getIcon() == -1);
    }
    return !data.contains(false);
}

//繪製底部時間
private void onDrawText(Canvas canvas, int i) {
    textPaint.setTextAlign(Paint.Align.CENTER);
    String text = TimeUtils.getDateHHmm(listItems.get(i).getTempStamp());
    int left = MARGIN_LEFT_ITEM + i * ITEM_WIDTH;
    int right = left + ITEM_WIDTH - 1;
    int bottom = mHeight - bottomTextHeight;
    Rect targetRect = new Rect(left, bottom, right, bottom + bottomTextHeight);
    Paint.FontMetricsInt fontMetrics = textPaint.getFontMetricsInt();
    int baseline = (targetRect.bottom + targetRect.top - fontMetrics.bottom - fontMetrics.top) / 2;
    textPaint.setTextSize(DisplayUtil.sp2px(getContext(), 12));
    if (i % 2 == 0)
        canvas.drawText(text, left + (ITEM_WIDTH - 1) / 2, baseline, textPaint);
}

public void drawLeftTempText(Canvas canvas) {
    if (listItems.size() > 0) {
        //畫最左側的文字
        textPaint.setTextAlign(Paint.Align.LEFT);
        textPaint.setTextSize(DisplayUtil.sp2px(getContext(), 13));
        canvas.drawText(maxTemp + "°", DisplayUtil.sp2px(getContext(), 15), tempBaseTop, textPaint);
        canvas.drawText(minTemp + "°", DisplayUtil.sp2px(getContext(), 15), tempBaseBottom, textPaint);
    }
}

//設定scrollerView的滾動條的位置,通過位置計算當前的時段
public void setScrollOffset(int offset, int maxScrollOffset, int scrollWidth) {
    this.maxScrollOffset = maxScrollOffset;
    this.scrollWidth = scrollWidth;
    scrollOffset = offset;
    currentItemIndex = calculateItemIndex();
    invalidate();
}

/**
 * 點距離左邊的位置
 *
 * @param i
 * @return
 */
private int getItemLeftMargin(int i) {
    int left = MARGIN_LEFT_ITEM + i * ITEM_WIDTH + (ITEM_WIDTH - 1) / 2;
    return left - scrollOffset;
}

/**
 * 點距離右邊的位置
 *
 * @param i
 * @return
 */
private int getItemRightMargin(int i) {
    int left = MARGIN_LEFT_ITEM + i * ITEM_WIDTH + (ITEM_WIDTH - 1) / 2;
    return scrollWidth - (left - scrollOffset);
}

//通過滾動條偏移量計算當前選擇的時刻
private int calculateItemIndex() {
    int x = getScrollBarX();
    int sum = MARGIN_LEFT_ITEM - ITEM_WIDTH;
    for (int i = 0; i < ITEM_SIZE; i++) {
        sum += ITEM_WIDTH;
        if (x < sum)
            return i;
    }
    return ITEM_SIZE - 1;
}

private int getScrollBarX() {
    int x = (ITEM_SIZE - 5) * ITEM_WIDTH * scrollOffset / maxScrollOffset;
    x = x + MARGIN_LEFT_ITEM;
    return x;
}

//計算溫度提示文字的運動軌跡
private int getTempBarY() {
    int x = getScrollBarX();
    int sum = MARGIN_LEFT_ITEM;
    Point startPoint = null, endPoint;
    int i;
    for (i = 0; i < ITEM_SIZE; i++) {
        sum += ITEM_WIDTH;
        if (x < sum) {
            startPoint = listItems.get(i).getTempPoint();
            break;
        }
    }
    if (i + 1 >= ITEM_SIZE || startPoint == null)
        return listItems.get(ITEM_SIZE - 1).getTempPoint().y;
    endPoint = listItems.get(i + 1).getTempPoint();
    int left = MARGIN_LEFT_ITEM + i * ITEM_WIDTH;
    int y = (int) (startPoint.y + (x - left) * 1.0 / ITEM_WIDTH * (endPoint.y - startPoint.y));
    return y;
}

} IndexHorizontalScrollView.javajava public class IndexHorizontalScrollView extends HorizontalScrollView {

private Today24HourView today24HourView;

public IndexHorizontalScrollView(Context context) {
    this(context, null);
}

public IndexHorizontalScrollView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public IndexHorizontalScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    int offset = computeHorizontalScrollOffset();
    int maxOffset = computeHorizontalScrollRange() - DisplayUtil.getScreenWidth(getContext());
    if (today24HourView != null) {
        today24HourView.setScrollOffset(offset, maxOffset, getWidth());
    }
}

public void setToday24HourView(Today24HourView today24HourView) {
    this.today24HourView = today24HourView;
    invalidate();
}

} xml中使用xml Activity中使用java binding.indexHorizontalScrollView.setToday24HourView(binding.today24Hour); binding.today24Hour.setHourItems(data) 實體類 WeatherHoursModel.javajava public class WeatherHoursModel { // 天氣圖示 private int icon; // 溫度 private int temperature; //天氣 private String weather; // 時間戳 private long tempStamp; //x,y軸 private Point tempPoint; } 程式碼中使用到的工具類java public static String getDateHHmm(long time) { String formatTime = new SimpleDateFormat("HH:mm").format(new Date(time)); return formatTime; }

public static int dip2px(Context context, float dipValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dipValue * scale + 0.5f);
}

public static int sp2px(Context context, float spValue) {
    final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
    return (int) (spValue * fontScale + 0.5f);
}

public static int getScreenWidth(Context context){
    DisplayMetrics dm = context.getResources().getDisplayMetrics();
    return dm.widthPixels;
}

```

到這裡就結束了,有寫的不好的地方還請指出。

參考連結\ Android 仿墨跡天氣24小時預報\ 24小時天氣(可滑動)\ MoJiDemo-作者zx391324751