HOME > Android > 文字と図形の描画

Android -文字と図形の描画-

文字と図形の描画

文字と図形描画するサンプルです。

GraphicsSample.java

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;

public class GraphicsSample extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(new GraphicsView(this));
  }

  class GraphicsView extends View {

    public GraphicsView(Context context) {
      super(context);
      setBackgroundColor(Color.WHITE);
    }

    @Override
    protected void onDraw(Canvas canvas) {

      Paint paint = new Paint();
      paint.setAntiAlias(true);

      paint.setTextSize(12);
      paint.setColor(Color.BLACK);

      //(1)ラインを描く
      canvas.drawText("(1)ラインを描く", 10, 20, paint);
      paint.setStrokeWidth(2);
      paint.setStyle(Paint.Style.STROKE);
      paint.setColor(Color.argb(255, 255, 0, 255));
      canvas.drawLine(20, 40, 20 + 20, 40, paint);

      //(2)ジグザグ線を描く
      paint.setColor(Color.BLACK);
      paint.setStrokeWidth(0);
      canvas.drawText("(2)ジグザグ線を描く", 10, 70, paint);
      paint.setColor(Color.argb(255, 255, 0, 0));
      paint.setStrokeWidth(2);
      Path path = new Path();
      path.moveTo(20, 90);
      path.lineTo(30, 110);
      path.lineTo(40, 100);
      path.lineTo(50, 110);
      path.lineTo(60, 90);
      path.lineTo(90, 90);
      canvas.drawPath(path, paint);

      //(3)長方形を描く
      paint.setColor(Color.BLACK);
      paint.setStrokeWidth(0);
      canvas.drawText("(3)長方形を描く", 10, 140, paint);
      paint.setColor(Color.GREEN);
      canvas.drawRect(new Rect(20, 160, 20 + 30, 160 + 20), paint);

      //(4)塗り潰しの楕円を描く
      paint.setColor(Color.BLACK);
      canvas.drawText("(4)塗り潰しの楕円を描く", 10, 210, paint);
      paint.setColor(Color.BLUE);
      paint.setStyle(Paint.Style.FILL);
      canvas.drawOval(new RectF(20, 230, 60, 250), paint);

      //(5)ニコちゃんマークを描く
      paint.setColor(Color.BLACK);
      canvas.drawText("(5)ニコちゃんマークを描く", 10, 280, paint);
      paint.setColor(Color.YELLOW);
      canvas.drawCircle(50, 330, 30, paint);
      paint.setColor(Color.BLACK);
      canvas.drawOval(new RectF(37, 319, 43, 327), paint);
      canvas.drawOval(new RectF(57, 319, 63, 327), paint);
      paint.setStyle(Paint.Style.STROKE);
      canvas.drawCircle(50, 330, 30, paint);
      canvas.drawArc(new RectF(35, 330, 65, 348), 180, -180, false, paint);
      canvas.drawText("v ピース-----!!", 100, 340, paint);
    }
  }
}
Copyright © 2018   MitoRoid  All Rights Reserved.