使用我的Android应用程序,我有一个可以缩放和平移的视图。在那个视图中,我想为以下几点画一条线。但是路径根本没有显示出来。我想知道这是否与点列表中的负数或大数字有关。
{ “×”: - 317, “Y”: - 744}, { “×”:50, “Y”: - 702}, { “×”:394, “Y”: - 663}, { “×”:718, “Y”: - 626}, { “×”:1023, “Y”: - 592}, { “×”:1310, “Y”: - 560}, { “×”:1581, “Y”: - 529}, { “×”:1837, “Y”: - 500}, { “×”:2079, “Y”: - 472}, { “×”:2951, “Y”:198}, { “×”:5997, “Y”:4780}, { “×”:4064, “Y”:4143}, { “×”:2686, “Y”:3689}, { “×”:1654, “Y”:3348}, { “×”:852, “Y”:3084}, { “×”:211, “Y”:2873}, { “×”: - 312, “Y”:2700}, { “×”: - 748, “Y”:2556}, { “×”: - 895, “Y”:2213}, { “×”: - 574, “Y”:569}, { “×”: - 317, “Y”: - 744}]}
这是代码段。
private final Paint paintStrokeArea = new Paint(Paint.ANTI_ALIAS_FLAG);
private Point[] viewArea = ...
public MyView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
paintStrokeArea.setColor(Color.WHITE);
paintStrokeArea.setStyle(Style.STROKE);
paintStrokeArea.setStrokeWidth(4.5f);
paintStrokeArea.setStrokeJoin(Join.MITER);
paintStrokeArea.setPathEffect(null);
}
public onDraw(Canvas) {
if (viewArea != null)
renderViewArea(viewArea, canvas, paintStroke);
}
public static void renderViewArea(Point[] area, Canvas canvas, Paint paint) {
if (area == null || canvas == null || paint == null)
return;
boolean first = true;
Path path = new Path();
Point last = new Point();
for (Point current : area) {
if (first) {
first = false;
} else {
path.moveTo(last.x, last.y);
path.lineTo(current.x, current.y);
}
last.set(current.x, current.y);
}
if (!first)
canvas.drawPath(path, paint);
}
答案 0 :(得分:1)
this post中描述了同样的问题。根据答案,出现问题是因为drawPath是在CPU中通过将其渲染到比传输到GPU中的位图而完成的。因为我的路径太大,所以无法将位图渲染(发送到)GPU。最好使用drawLines,因为它直接使用GPU。这是我封装的辅助类。
package eu.level12.tools;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
/**
* Provides several static methods for drawing onto Android's canvas.
* Hardware-accelerated methods are named with the prefix render while others
* begin with draw.
*
* @author Matthias Heise
*
*/
public final class DrawingTools {
/**
* Draws the line specified by the given path using hardware-accelerated
* method Canvas.drawLines. Has no effect if either argument is null or if
* the line consists of less than two points.
*
* @param path
* A path of points that specifies the line.
* @param canvas
* The canvas onto which the line should be drawn.
* @param paint
* The paint argument that specifies how the line is drawn.
*/
public static void renderLine(Point[] path, Canvas canvas, Paint paint) {
if (path == null || canvas == null || paint == null || path.length <= 1)
return;
final float[] lines = new float[(path.length - 1) * 4];
int index = 0;
final Point last = new Point();
boolean first = true;
for (Point current : path) {
if (first) {
first = false;
} else {
// start point
lines[index] = last.x;
lines[index + 1] = last.y;
// end point
lines[index + 2] = current.x;
lines[index + 3] = current.y;
index += 4;
}
last.set(current.x, current.y);
}
if (!first)
canvas.drawLines(lines, paint);
}
}