Xamarinで遊んでみる
やりたいこと
レシピ
教科書
インストール
Mac OS Update
Xcode Update
Visual Studio for mac Install
実機の準備(例:iOS11.03のiPhone6s)
Xcodeの設定
Visual Studioでiphoneでの実機ビルドを行う為に、Xcodeでダミープロジェクトをつくってバンドル識別子を取得する必要がある
アカウントの登録
プロジェクトの作成(ここでバンドル識別子が取得できる)
Single View Application
参考:
Visual Studioのプロジェクトの作成(設定)・ビルド
新しいプロジェクトを作る
Single View Application
作成したプロジェクトのInfo.plistのバンドル識別子を上記の物に変更する
上方タブのDebug -> iPhoneに設定し、横の▷(実行ボタン)をクリック
iPhone上で設定→一般→プロファイル→信頼をクリック
上記手順で実行できる
Xamarinの初期コード構成
Main.cs
- アプリケーションのエントリーポイント
Info.plist
- アプリケーション名やバージョンなどを設定できるファイル
Main.storyboard
- 画面を定義する為のストーリーボードファイル
ViewController.cs
- ストーリーボードの画面に対してロジックを奇術するためのクラス
いくつかコードをトライ
ボタンなど基本の操作のサンプル
磁気センサ
GPS
加速度センサ
加速度センサを使う
ViewControllerを以下を参考に書きかえ
上記コードの解説
画面サイズ基準でラベルサイズを指定
// Viewのサイズを取得 layoutW = View.Bounds.Width; layoutH = View.Bounds.Height; // Viewサイズを元にLabelサイズを指定 textW = layoutW / 2; textH = layoutH / 6;
デバッグ出力
System.Diagnostics.Debug.WriteLine("Width: {0}, Height: {1}", layoutW, layoutH);
ラベルの作成
// Label作成&配置 var sensorText = new UILabel(new CGRect(layoutW / 2 - textW / 2, layoutH / 2 - textH / 2, textW, textH)); sensorText.BackgroundColor = UIColor.FromRGB(192, 192, 192); sensorText.Lines = 0; sensorText.TextAlignment = UITextAlignment.Center; sensorText.LineBreakMode = UILineBreakMode.TailTruncation; View.AddSubview(sensorText);
加速度の表示&反映
Frameとは:[iPhone] UIView の frame と bounds の違い | Sun Limited Mt.
var textLoc = sensorText.Frame; motionManager = new CMMotionManager(); if (motionManager.AccelerometerAvailable) { // Accelerometer Update間隔 motionManager.AccelerometerUpdateInterval = 0.015; // UpdateがQueueに入る度に処理を行う(多分) motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) => { sensorText.Text = string.Format("X = {0:N4}\nY = {1:N4}", data.Acceleration.X, data.Acceleration.Y); // 現在の位置を取得 nowX = sensorText.Frame.X; nowY = sensorText.Frame.Y; System.Diagnostics.Debug.WriteLine("nowX: {0}, nowY: {1}", nowX, nowY); // Viewをはみ出さないようにAccelerometerの値によってLabelを移動 if (nowX + (nfloat)data.Acceleration.X * 10 > 0 && nowX + (nfloat)data.Acceleration.X * 10 < layoutW - textW) textLoc.X = nowX + (nfloat)data.Acceleration.X * 10; if (nowY - (nfloat)data.Acceleration.Y * 10 > 0 && nowY - (nfloat)data.Acceleration.Y * 10 < layoutH - textH) textLoc.Y = nowY - (nfloat)data.Acceleration.Y * 10; sensorText.Frame = textLoc; }); }
動作画面
この画面の中央に加速度が表示される
Bluetoothを使う
ハマり個所
所感
これからロボットの操作用IFにスマホを使っていきたい♪