2

I want to create graph (with edges and vertices), to implement a problem called 3-color. I just need a little guidance on how to start, should i use a multiple views and draw each view as a circle, and then how can i connect lines (edges) between the views? should i work with pixels all the time or there is another way, more simple one because calculate pixels when dealing with big graphs (more than 10 vertices) is complicated.

thanks.

azizbekian
  • 60,783
  • 13
  • 169
  • 249
T.S
  • 911
  • 8
  • 24
  • check this library https://github.com/lecho/hellocharts-android – amzer Apr 04 '17 at 08:14
  • Im not talking about graphs in this manner, im talking about graphs with edges and vertices, you can google it and see what im talking about. – T.S Apr 04 '17 at 08:17

2 Answers2

1

What you want is called drawing on Canvas.

As a basic example you can see this code, which will create 2 vertices and an edge connecting them:

public class MyView extends View {

    private final Paint p;
    private final Path path;
    private final Point point1;
    private final Point point2;

    public MyView(Context context) {
        super(context);

        p = new Paint(Paint.ANTI_ALIAS_FLAG);
        p.setStrokeWidth(10);
        path = new Path();

        point1 = new Point(200, 300);
        point2 = new Point(700, 800);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // draw first vertex
        p.setStyle(Paint.Style.FILL);
        p.setColor(Color.GREEN);
        canvas.drawCircle(point1.x, point1.y, 15, p);

        // draw the edge
        path.reset();
        path.moveTo(point1.x, point1.y);
        path.lineTo(point2.x, point2.y);
        p.setStyle(Paint.Style.STROKE);
        p.setColor(Color.CYAN);
        canvas.drawPath(path, p);

        // draw second vertex
        p.setStyle(Paint.Style.FILL);
        p.setColor(Color.BLUE);
        canvas.drawCircle(point2.x, point2.y, 15, p);
    }
}

Which will result in this:

enter image description here

azizbekian
  • 60,783
  • 13
  • 169
  • 249
  • The question is how can i have a click listener to this point? i want to change the color of the vertex when someone thouches the vertex. thanks. i also need a reference to each vertex and each edge so i don't know if it is the right way. – T.S Apr 04 '17 at 18:37
  • You have to handle touch event on your own, because it's a custom view. Basically, you have to listen for touch event, get the (x,y) corrdinate of it, see what vertex is laid out in that coordinate and handle click event. There's no straightforward way to do that. That's why it's called **custom** view. – azizbekian Apr 04 '17 at 18:39
1

I found this library which is a good source: https://github.com/LordVulkan/Graphs

T.S
  • 911
  • 8
  • 24