android用canvas画出线段和箭头
public class MainActivity extends AppCompatActivity { Button button; private ImageView iv_canvas; private Bitmap baseBitmap; private Canvas canvas; private Paint paint; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); paint = new Paint(); paint.setStrokeWidth(1); paint.setColor(Color.RED); iv_canvas = findViewById(R.id.iv_canvas); button=findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawTria((float) 300, (float) 100, (float) 400, (float) 100, 30, 10); } }); } protected void drawTria(float fromX, float fromY, float toX, float toY, int heigth, int bottom) { // heigth和bottom分别为三角形的高与底的一半,调节三角形大小 baseBitmap = Bitmap.createBitmap(iv_canvas.getWidth(), iv_canvas.getHeight(), Bitmap.Config.ARGB_8888); canvas = new Canvas(baseBitmap); canvas.drawColor(Color.YELLOW);// 设置底色 canvas.drawLine(fromX, fromY, toX, toY, paint); float juli = (float) Math.sqrt((toX - fromX) * (toX - fromX) + (toY - fromY) * (toY - fromY));// 获取线段距离 float juliX = toX - fromX;// 有正负,不要取绝对值 float juliY = toY - fromY;// 有正负,不要取绝对值 float dianX = toX - (heigth / juli * juliX); float dianY = toY - (heigth / juli * juliY); float dian2X = fromX + (heigth / juli * juliX); float dian2Y = fromY + (heigth / juli * juliY); //终点的箭头 Path path = new Path(); path.moveTo(toX, toY);// 此点为三边形的起点 path.lineTo(dianX + (bottom / juli * juliY), dianY - (bottom / juli * juliX)); path.lineTo(dianX - (bottom / juli * juliY), dianY + (bottom / juli * juliX)); path.close(); // 使这些点构成封闭的三边形 canvas.drawPath(path, paint); //显示图像 iv_canvas.setImageBitmap(baseBitmap); }
}
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.administrator.myapplication.MainActivity"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="127dp" android:text="画线" android:visibility="visible" /> <ImageView android:id="@+id/iv_canvas" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginBottom="10dp" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>