コンパスビューの作成例android canvas compass


次の例では、Viewクラスを拡張することでコンパスViewを作成します.従来のコンパスの上昇矢印を使用して方向を示します.完成したら、図4-3と同じように見えるはずです.
 
コンパスはUIコントロールの例であり、SDKツールボックスのTextViewとButtonとは異なり、完全に異なる視覚表示が必要であり、優れたコントロールになるようにします.
 
10章では、このコンパスViewとデバイス内に構築された重力加速計を使用して、ユーザーの現在の方向を表示します.11章では、より高度なCanvasペイントテクニックを学び、その外観を劇的に改善します.
図4-3
 
1.コンパスを含む新しいコンパスプロジェクトを作成
View
それを持つ
Activity
.作成
CompassView
クラスを拡張
View
.コンストラクション関数を作成して実行
View
コードでインスタンス化するか、リソースで
layout
の膨張.新しい
initCompassView
メソッドを使用してコントロールを初期化し、各コンストラクション関数で呼び出します.
package com.paad.compass;

import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.*;
import android.view.*;
import android.util.AttributeSet;
import android.content.res.Resources;

public class CompassView extends View {

	public CompassView(Context context) {
		super(context);
		initCompassView();
	}
	
	public CompassView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initCompassView();
	}
	
	public CompassView(Context context, AttributeSet ats, int defaultStyle) {
		super(context, ats, defaultStyle);
		initCompassView();
	}
	
	protected void initCompassView() {
		setFocusable(true);
	}
}

2.コンパスコントロールは、キャンバスが許容する可能な限り多くの空間を常に1つの円で占有する必要があります.書き換える
onMeasure
最小エッジを計算する方法、
setMeasuredDimension
で行ないます.
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// The compass is a circle that fills as much space as possible.
		// Set the measured dimensions by figuring out the shortest boundary,
		// height or width.
		int measuredWidth = measure(widthMeasureSpec);
		int measuredHeight = measure(heightMeasureSpec);
		int d = Math.min(measuredWidth, measuredHeight);
		setMeasuredDimension(d, d);
	}

	private int measure(int measureSpec) {
		int result = 0;
		// Decode the measurement specifications.
		int specMode = MeasureSpec.getMode(measureSpec);
		int specSize = MeasureSpec.getSize(measureSpec);
		
		if (specMode == MeasureSpec.UNSPECIFIED) {
			// Return a default size of 200 if no bounds are specified.
			result = 200;
		} else {
			// As you want to fill the available space
			// always return the full available bounds.
			result = specSize;
		}
		return result;
	}

3.コンパスを描画するときに使用するリソースファイル(色と文字列)を2つ作成します.
3.1. テキスト文字列リソースの作成
/
res/values/strings.xml.
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
	<string name=”app_name”>Compass</string>
	<string name=”cardinal_north”>N</string>
	<string name=”cardinal_east”>E</string>
	<string name=”cardinal_south”>S</string>
	<string name=”cardinal_west”>W</string>
</resources>

3.2. カラーアセットを作成するには
/r
es/values/colors.xml.
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
	<color name=”background_color”>#F555</color>
	<color name=”marker_color”>#AFFF</color>
	<color name=”text_color”>#AF00</color>
</resources>

4.CompassViewクラスに戻ります.方向を表示するプロパティを作成し、getメソッドとsetメソッドを作成します.
	private float bearing;
	public void setBearing(float _bearing) {
		bearing = _bearing;
	}
	 
	public float getBearing() {
		return bearing;
	}

5.次に、
initCompassView
メソッドで、
3
ステップで作成したリソースの参照.クラスの役割ドメインの方法で文字列値と色値から作成された
Paint
オブジェクト.次のステップでは、これらのオブジェクトを使用してコンパスを描画します.
	private Paint markerPaint;
	private Paint textPaint;
	private Paint circlePaint;
	private String northString;
	private String eastString;
	private String southString;
	private String westString;
	private int textHeight;
	 
	protected void initCompassView() {
		setFocusable(true);
		 
		circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		circlePaint.setColor(R.color. background_color);
		circlePaint.setStrokeWidth(1);
		circlePaint.setStyle(Paint.Style.FILL_AND_STROKE);
		
		Resources r = this.getResources();
		
		northString = r.getString(R.string.cardinal_north);
		eastString = r.getString(R.string.cardinal_east);
		southString = r.getString(R.string.cardinal_south);
		westString = r.getString(R.string.cardinal_west);
		
		textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		textPaint.setColor(r.getColor(R.color.text_color));
		
		textHeight = (int)textPaint.measureText(“yY”);
		
		markerPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		markerPaint.setColor(r.getColor(R.color.marker_color));
	}

6.最後の一歩は第
5
ステップで作成した文字列と
Paint
の双曲線コサインを返します.次のコードクリップは、限られたヒントのみを与えます.あなたは第
11
章の詳細
Canvas
を選択します.
Paint
効果の詳細.
6.1. まずonDrawメソッドを書き直します.
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
	}

6.2. コントロールの中心を見つけ、最小エッジの長さをコンパスの半径として格納します.
int px = getMeasuredWidth() / 2;
int py = getMeasuredHeight() /2 ;
int radius = Math.min(px, py);

6.3.
 
drawCircleメソッドを使用して外枠を描画し、背景の色は手順5で作成したcirclePaintオブジェクトを使用します.
// Draw the background
canvas.drawCircle(px, py, radius, circlePaint);

6.4. コンパスは、回転パネルを介して現在の指向を表示するので、現在の方向は常にデバイスの先端にあります.この効果を達成するには、現在の方向とは反対の方向にキャンバスを回転させます.
// Rotate our perspective so that the ‘top’ is
// facing the current bearing.
canvas.save();
canvas.rotate(-bearing, px, py);

6.5. 今残っているのは、文字盤を描くことです.キャンバスを1週間回転し、
15
°タグを1つずつ描画
45
°方向文字列を描画します.
	int textWidth = (int)textPaint.measureText(“W”);
	int cardinalX = px-textWidth/2;
	int cardinalY = py-radius+textHeight;
	 
	// Draw the marker every 15 degrees and text every 45.
	for (int i = 0; i < 24; i++) {
		// Draw a marker.
		canvas.drawLine(px, py-radius, px, py-radius+10, markerPaint);
		canvas.save();
		canvas.translate(0, textHeight);
		
		// Draw the cardinal points
		if (i % 6 == 0) {
			String dirString = “”;
			switch (i)
			{
			case(0) :
			{
				dirString = northString;
				int arrowY = 2*textHeight;
				canvas.drawLine(px, arrowY, px-5, 3*textHeight, markerPaint);
				canvas.drawLine(px, arrowY, px+5, 3*textHeight, markerPaint);
				break;
			}
			case(6) : dirString = eastString; break;
			case(12) : dirString = southString; break;
			case(18) : dirString = westString; break;
			}
			canvas.drawText(dirString, cardinalX, cardinalY, textPaint);
		} else if (i % 3 == 0) {
			// Draw the text every alternate 45deg
			String angle = String.valueOf(i*15);
			float angleTextWidth = textPaint.measureText(angle);
			int angleTextX = (int)(px-angleTextWidth/2);
			int angleTextY = py-radius+textHeight;
			canvas.drawText(angle, angleTextX, angleTextY, textPaint);
		}
		canvas.restore();
		canvas.rotate(15, px, py);
	}
	
	canvas.restore();

7.コンパスを確認するためにmainを修正する.xmlリソースは、あなたのCompassViewを使用してTextViewを置き換えます.このプロセスは、次の章でより詳細に説明されます.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <com.pad.compass.view.CompassView
	android:id="@+id/compass"  
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
    />
</LinearLayout>


8.Activityを実行すると、コンパスが表示されます.10章では、CompassViewをデバイスのコンパスにバインドする方法について説明します.
Sample Code:
       http://files.cnblogs.com/xirihanlin/[email protected]
Sampleの図: