自定义曲线图Canvas.drawPath()失效解决方法
一、现象
公司APP开发一个曲线图展示一些数据,在完成后测试时发现了一个问题:在部分机型(比如:米4 系统 6.0.1)上绘制曲线图时加载第一屏30条数据时没有问题,而滑动加载第二屏数据时所有数据的连线消失。但是其他数据包括连线上的点都没有消失。而在其他机型上没有问题(比如红米 Note 8 系统 9),实现代码如下:
private void drawCurve(Canvas canvas, ArrayList<PointF> list, int lineColor) {
if (list == null || list.size() == 0) {
return;
}
List<PointF> NewPoints = new ArrayList<>();
NewPoints.addAll(list);
float lX = 0;
float lY = 0;
fatPath.reset();
fatPath.moveTo(NewPoints.get(0).x, NewPoints.get(0).y);
for (int i = 1; i < NewPoints.size(); i++) {
PointF p = NewPoints.get(i);
PointF firstPointF = NewPoints.get(i - 1);
float x1 = firstPointF.x + lX;
float y1 = firstPointF.y + lY;
PointF secondPointF = NewPoints.get(i + 1 < NewPoints.size() ? i + 1 : i);
lX = (secondPointF.x - firstPointF.x) / 2 * smoothness;
lY = (secondPointF.y - firstPointF.y) / 2 * smoothness;
float x2 = p.x - lX;
float y2 = p.y - lY;
if (y1 == p.y) {
y2 = y1;
}
fatPath.cubicTo(x1, y1, x2, y2, p.x, p.y);
}
mWFLinePaint.setColor(lineColor);
canvas.drawPath(fatPath, mWFLinePaint);
}
二、原因
经过排查发现一次性加载30条以上的数据时超过30条的数据都丢失了连线。并非代码问题。最终发现是硬件加速导致连线绘制丢失。
三、解决方法
1. 在Manifinest文件里面禁止硬件加速
不推荐这种做法,这会使所有的view包括程序中的surfaceView都禁止加速了,影响范围不可控。
2. 在自定义控件的构造函数里面执行this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
代码如下:
public WeightFatView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
mContext = context;
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.barchar_style);
barInterval = (int) typedArray.getDimension(R.styleable.barchar_style_barInterval, dp2Px(30));
bar_color = typedArray.getColor(R.styleable.barchar_style_bar_color, Color.WHITE);
barWidth = (int) typedArray.getDimension(R.styleable.barchar_style_barWidth, dp2Px(16));
top_text_size = (int) typedArray.getDimension(R.styleable.barchar_style_bottom_text_size, sp2Px(45));
top_text_size_2 = (int) typedArray.getDimension(R.styleable.barchar_style_bottom_text_size, sp2Px(24));
top_text_size_3 = (int) typedArray.getDimension(R.styleable.barchar_style_bottom_text_size, sp2Px(18));
top_text_size_4 = (int) typedArray.getDimension(R.styleable.barchar_style_bottom_text_size, sp2Px(12));
top_text_color = typedArray.getColor(R.styleable.barchar_style_bottom_text_color, Color.parseColor("#93bdfb"));
top_text_color_2 = typedArray.getColor(R.styleable.barchar_style_bottom_text_color, Color.parseColor("#f58c28"));
bottom_line_color = typedArray.getColor(R.styleable.barchar_style_bottom_line_color, Color.parseColor("#c1c1c1"));
typedArray.recycle();
initPaint();
weightBitmap = drawable2Bitmap(getResources().getDrawable(R.drawable.icon_circle_weight));
fatBitmap = drawable2Bitmap(getResources().getDrawable(R.drawable.icon_circle_fat));
selectBitmap = drawable2Bitmap(getResources().getDrawable(R.drawable.bg_rect_select));
}
到这里问题就解决了,希望可以解决小伙伴的问题。