# 仿墨迹24小时天气自定义View

``````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;
}
``````

``````public Point(int x, int y) {
this.x = x;
this.y = y;
}
``````

tempBaseTop和tempBaseBottom是在初始化中按高度比例来分

``````tempBaseTop = (mHeight - bottomTextHeight) / 3;
tempBaseBottom = (mHeight - bottomTextHeight) * 3 / 4;
``````

bottomTextHeight是下方数字文本高度

``````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);
``````

01.jpg

02.jpg

``````PathEffect pathEffect = new CornerPathEffect(180);
linePaint.setPathEffect(pathEffect);
``````

CornerPathEffect的作用是通过将线段之间的任何锐角替换为指定半径的圆角来转换绘制的几何图形（STROKE 或 FILL 样式）。参数：半径 - 线段之间的圆角

03.jpg

``````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);
}
}
}
}
``````
``````private boolean getGoneBehind(int index) {
List<Boolean> data = new ArrayList<>();
for (int k = index; k < listItems.size(); k++) {
}
return !data.contains(false);
}
``````

``````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();
}
}
``````

04.jpg

``````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);
}
}
}
}
``````

``````/**
* 点距离左边的位置
*
* @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的宽度

24小时天气自定义view是被另一个自定义View中包含的，它继承于HorizontalScrollView，需要修改的代码如下

``````    @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（）滚动视图的滚动范围是其所有子视图的总宽度

``````    //设置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中代码如下

``````<com.weather.gorgeous.custom_view.IndexHorizontalScrollView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:scrollbars="none">
<com.weather.gorgeous.custom_view.Today24HourView
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.weather.gorgeous.custom_view.IndexHorizontalScrollView>
``````
05.gif

``````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);
}
``````
``````    //计算温度提示文字的运动轨迹
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;
}
``````
``````    private int getScrollBarX() {
int x = (ITEM_SIZE - 5) * ITEM_WIDTH * scrollOffset / maxScrollOffset;
x = x + MARGIN_LEFT_ITEM;
return x;
}
``````

06.gif

``````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"));
}
``````

07.gif.gif

Today24HourView.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);
}
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++) {
}
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.java

``````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中使用

``````<com.weather.gorgeous.custom_view.IndexHorizontalScrollView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:scrollbars="none">
<com.weather.gorgeous.custom_view.Today24HourView
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.weather.gorgeous.custom_view.IndexHorizontalScrollView>
``````

Activity中使用

``````binding.indexHorizontalScrollView.setToday24HourView(binding.today24Hour);
binding.today24Hour.setHourItems(data)
``````

``````public class WeatherHoursModel {
// 天气图标
private int icon;
// 温度
private int temperature;
//天气
private String weather;
// 时间戳
private long tempStamp;
//x,y轴
private Point tempPoint;
}
``````

``````    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;
}
``````

Demo地址-Kotlin

• 序言：七十年代末，一起剥皮案震惊了整个滨河市，随后出现的几起案子，更是在滨河造成了极大的恐慌，老刑警刘岩，带你破解...
沈念sama阅读 143,540评论 1 302
• 序言：滨河连续发生了三起死亡事件，死亡现场离奇诡异，居然都是意外死亡，警方通过查阅死者的电脑和手机，发现死者居然都...
沈念sama阅读 61,539评论 1 258
• 文/潘晓璐 我一进店门，熙熙楼的掌柜王于贵愁眉苦脸地迎上来，“玉大人，你说我怎么就摊上这事。” “怎么了？”我有些...
开封第一讲书人阅读 95,005评论 0 213
• 文/不坏的土叔 我叫张陵，是天一观的道长。 经常有香客问我，道长，这世上最难降的妖魔是什么？ 我笑而不...
开封第一讲书人阅读 41,159评论 0 180
• 正文 为了忘掉前任，我火速办了婚礼，结果婚礼上，老公的妹妹穿的比我还像新娘。我一直安慰自己，他们只是感情好，可当我...
茶点故事阅读 48,946评论 1 258
• 文/花漫 我一把揭开白布。 她就那样静静地躺着，像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上，一...
开封第一讲书人阅读 38,864评论 1 178
• 那天，我揣着相机与录音，去河边找鬼。 笑死，一个胖子当着我的面吹牛，可吹牛的内容都是我干的。 我是一名探鬼主播，决...
沈念sama阅读 30,468评论 2 273
• 文/苍兰香墨 我猛地睁开眼，长吁一口气：“原来是场噩梦啊……” “哼！你这毒妇竟也来了？” 一声冷哼从身侧响起，我...
开封第一讲书人阅读 29,218评论 0 167
• 想象着我的养父在大火中拼命挣扎，窒息，最后皮肤化为焦炭。我心中就已经是抑制不住地欢快，这就叫做以其人之道，还治其人...
爱写小说的胖达阅读 29,070评论 6 234
• 序言：老挝万荣一对情侣失踪，失踪者是张志新（化名）和其女友刘颖，没想到半个月后，有当地人在树林里发现了一具尸体，经...
沈念sama阅读 32,574评论 0 213
• 正文 独居荒郊野岭守林人离奇死亡，尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
茶点故事阅读 29,353评论 2 215
• 正文 我和宋清朗相恋三年，在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
茶点故事阅读 30,683评论 1 232
• 白月光回国，霸总把我这个替身辞退。还一脸阴沉的警告我。[不要出现在思思面前， 不然我有一百种方法让你生不如死。]我...
爱写小说的胖达阅读 24,270评论 0 32
• 序言：一个原本活蹦乱跳的男人离奇死亡，死状恐怖，灵堂内的尸体忽然破棺而出，到底是诈尸还是另有隐情，我是刑警宁泽，带...
沈念sama阅读 27,168评论 2 214
• 正文 年R本政府宣布，位于F岛的核电站，受9级特大地震影响，放射性物质发生泄漏。R本人自食恶果不足惜，却给世界环境...
茶点故事阅读 31,591评论 3 210
• 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹，春花似锦、人声如沸。这庄子的主人今日做“春日...
开封第一讲书人阅读 25,638评论 0 9
• 文/苍兰香墨 我抬头看了看天上的太阳。三九已至，却和暖如春，着一层夹袄步出监牢的瞬间，已是汗流浃背。 一阵脚步声响...
开封第一讲书人阅读 26,035评论 0 166
• 我被黑心中介骗来泰国打工， 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留，地道东北人。 一个月前我还...
沈念sama阅读 33,590评论 2 232
• 正文 我出身青楼，却偏偏与公主长得像，于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子，可洞房花烛夜当晚...
茶点故事阅读 33,685评论 2 233