Thursday, 2 March 2017

How To Draw Triangle In Android

DrawView.java

package com.androidsimplifycodes.example;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;

public class DrawView extends View {

    protected Paint paint;

    public DrawView(Context context) {
        super(context);
        initView();
    }

    private void initView() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.BLUE);
        paint.setStrokeWidth(6f);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawTriangle(getWidth() / 2, getHeight() / 2, 350, canvas, paint);
    }

    public void drawTriangle(int x, int y, int width, Canvas canvas, Paint paint) {
        int halfWidth = width / 2;

        Path path = new Path();
        path.moveTo(x, y - halfWidth);
        path.lineTo(x - halfWidth, y + halfWidth);
        path.lineTo(x + halfWidth, y + halfWidth);
        path.lineTo(x, y - halfWidth);
        path.close();

        canvas.drawPath(path, paint);
    }
}
MainActivity.java

package com.androidsimplifycodes.example;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(new DrawView(this));
    }
}
Output :