Canvas drehen

  • Antworten:1
Robbiani Renato
  • Forum-Beiträge: 609

22.02.2021, 21:13:11 via Website

Hallo zusammen

Ich möchte mir einen Kompass App bauen. Die Nadel dreht sich schon recht gut. Aber die Kreiseinteilung drumherum dreht sich ebenfalls mit. Ich möchte aber, dass sich nur der Pfeil dreht und der Kreis stehen bleibt.

Wie kann ich das machen? Kann ich zwei Canvas übereinander Legen oder wie kann ich das machen.

package ch.robbisoft.kompass;

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

public class KompassnadelView extends View {

private float winkel=0;
private float werty=0;
private float wertz=0;
private Paint zeichenfarbe = new Paint();
private Paint textPaint;
private Paint kreisPaint;

public float getWerty() {
    return werty;
}

public void setWerty(float werty) {
    this.werty = werty;
}

public float getWertz() {
    return wertz;
}

public void setWertz(float wertz) {
    this.wertz = wertz;
}

public float getWinkel() {
    return winkel;
}

public void setWinkel(float winkel) {
    this.winkel = winkel;
    invalidate();
}

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

    zeichenfarbe.setAntiAlias(true);
    zeichenfarbe.setColor(Color.WHITE);
    zeichenfarbe.setStyle(Paint.Style.FILL);

    //Schreibfarbe
    textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
    textPaint.setColor(Color.GREEN);
    textPaint.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics()));
    textPaint.setTextAlign(Paint.Align.LEFT);
}

@Override
protected void onDraw(Canvas canvas) {

    canvas.drawColor(Color.BLACK);

    int breite = canvas.getWidth();
    int hoehe = canvas.getHeight();

// Den kleineren der beiden Werte
int laenge = Math.min(breite, hoehe);

    Path pfad = new Path();
    pfad.moveTo(0, -laenge/2);
    pfad.lineTo(laenge/20, laenge/2);
    pfad.lineTo(-laenge/20, laenge/2);
    pfad.close();

    canvas.translate(breite / 2, hoehe / 2);
    canvas.rotate(winkel);
    canvas.drawPath(pfad, zeichenfarbe);

    //Kreis Zeichnen
    kreisPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
    kreisPaint.setColor(Color.YELLOW);
    kreisPaint.setStyle(Paint.Style.STROKE);
    canvas.drawCircle(0, 0, (breite / 2), kreisPaint);

    //Text ausgeben
    Paint.FontMetrics metric = textPaint.getFontMetrics();
    int textHeight = (int) Math.ceil(metric.descent - metric.ascent);
    int y = (int)(textHeight - metric.descent);
    canvas.drawText(Float.toString(winkel), 0, y, textPaint);
    canvas.drawText(Float.toString(werty), 0, y+100, textPaint);
    canvas.drawText(Float.toString(wertz), 0, y+200, textPaint);
}

}

Gruss Renato

Kommentieren