利用path的lineto方法绘制一个三角形

首先还是在布局文件中放入一个button和一个Imageview

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="绘制(path)"
        android:onClick="onClick" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerInParent="true"
        android:background="#ff669900"
        />

RelativeLayout>

然后就可以开始绘制了,主要是利用点的首尾连接

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends Activity {

    private ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView=(ImageView) findViewById(R.id.imageView1);
    }

    public void onClick(View v){
        //1.bitmap (背景对象)
        Bitmap bitmap=
        Bitmap.createBitmap(200,200,
        Config.ARGB_8888);
        //2.构建画布对象(Canvas)
        Canvas c=new Canvas(bitmap);
        //3.构建画笔对象(Paint)
        Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.RED);
        //4.执行绘制动作(绘制一个路径)
        paint.setStyle(Style.STROKE);//必须要设置
        paint.setStrokeWidth(2);
        Path p=new Path();//通过此对象绘制一个轨迹
        p.moveTo(50,50);//起始点
        p.lineTo(50,10);//终止点
        p.lineTo(100,50);//起始点(50,10),终止点
        p.close();//形成闭环
        c.drawPath(p, paint);
        //5.显示绘制的对象
        imageView.setImageBitmap(bitmap);

    }

}

你可能感兴趣的:(工具)