【C#】Labelコントロールでテキストフォントのサイズを自動調節する
現在携わっているブロジェクトで実装した内容をメモ代わりに残そうと思います。
Excelでいうところの「縮小して全体を表示する」をWindowsFormのLabelコントロールで実装する要件が出てきた為、コントロールの矩形サイズから自動でフォントサイズを調節するユーザコントロールを作成しました。
WindowsFormのC#業務アプリはまだしばらく無くならないと思いますので、今後のプロジェクトの参考資料かな…。
namespace WindowsFormsApplication1 { partial class AutoFontSizeLabel { /// <summary> /// 必要なデザイナー変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region コンポーネント デザイナーで生成されたコード /// <summary> /// デザイナー サポートに必要なメソッドです。このメソッドの内容を /// コード エディターで変更しないでください。 /// </summary> private void InitializeComponent() { this.SuspendLayout(); this.ResumeLayout(false); } #endregion } }
CalcFontSizeメソッドはMeasureStringメソッドを呼び出す際、引数の文字列が空文字の場合、SizeFが正しく計算されないため、空文字が引数で渡ってきた場合、初期値にそれぞれ0.1を設定しています。
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class AutoFontSizeLabel : Label { #region クラス変数 /// <summary> /// フォントサイズを自動で算出するかのフラグ /// </summary> private bool mAutoFontSize = false; #endregion #region プロパティ /// <summary> /// フォントサイズを自動計算するかの値を取得または設定します。 /// </summary> [Browsable(true)] [Category("表示")] [Description("フォントサイズを自動で計算するかの値を取得または設定します。")] public bool AutoFontSize { set { this.mAutoFontSize = value; Invalidate(); } get { return this.mAutoFontSize; } } #endregion #region コンストラクタ /// <summary> /// クラスの新しいインスタンスを初期化します。 /// </summary> public AutoFontSizeLabel() { InitializeComponent(); } #endregion #region overrideメソッド /// <summary> /// 描画処理 /// </summary> /// <param name="pevent"></param> protected override void OnPaint(PaintEventArgs pevent) { // 描画先のGraphicsオブジェクトを取得する var g = pevent.Graphics; // 描画に関連する値をコントロールのプロパティ等から取得する int height = this.Height; int width = this.Width; // 描画領域を指定する var rect = new Rectangle(0, 0, width, height); // 背景描画用のブラシを生成する using (backColorBrush = new SolidBrush(this.BackColor)) { // 背景を描画する g.FillRectangle(backColorBrush, rect); } var size = new Size(width, height); var fontSize = CalcFontSize(this.Text, size, g); var font = this.Font; if (this.mAutoFontSize) { // 自動算出する場合、計算しておいたフォントサイズでフォントのインスタンスを再生成する font = new Font(this.Font.Name, fontSize); } // StringAlignmentからContentAlignmentへ変換する var stringFormat = new StringFormat(); var num = (Int32)System.Math.Log((Double)this.TextAlign, 2); stringFormat.LineAlignment = (StringAlignment)(num / 4); stringFormat.Alignment = (StringAlignment)(num % 4); // 文字描画用のブラシを生成する using (var foreColorBrush = new SolidBrush(this.ForeColor)) { // 文字を描画する g.DrawString(this.Text, font, foreColorBrush, rect, stringFormat); } } #endregion #region privateメソッド /// <summary> /// 引数で指定されたグラフィックオブジェクトに描画する最適なフォントサイズを算出します。 /// </summary> /// <param name="str">出力する文字列</param> /// <param name="size">サイズ</param> /// <param name="g">グラフィックオブジェクト</param> /// <returns>フォントサイズ</returns> private float CalcFontSize(string str, Size size, Graphics g) { var s = new SizeF(0.1F, 0.1F); var a = 0.1F; var b = 0.1F; if (!string.IsNullOrEmpty(str)) { s = g.MeasureString(str, new Font(this.Font.Name, this.Font.Size)); a = (size.Width / s.Width); b = (size.Height / s.Height); } return (a < b) ? a : b; } #endregion } }
DrawStringメソッドで文字を描画すると微妙に右にずれます。掲示板などで色々議論されていますが、今回未対応です。以下のサイトが参考になるかと思います。
VB.netで文字を正確な位置に描く。
【Xamarin】落ちないアプリの作成【Android】
Xamarinが無料になってから、色々なところでかなり盛り上がっているように感じます。
そんな私も最近Xamarin勉強中です笑
今回は、Xamarinについて調べているうちに、面白い内容を見つけたので、試すついでに記事にしてみました。
はじめに
タイトルになっている落ちないアプリ。
そんなものはありません!!
だけど、開発者としては落ちないアプリを作っていきたいですよね?
どうやって作るのか
上で書いたように絶対に落ちないアプリを作るというのは現状不可能です。
- 多種多様な端末、バージョン
- メモリ不足
- バグ
etc...
そこで、例外をキャッチして、とりあえず落ちないようにしてしまおうという考えです。
例外ハンドラ
androidで例外ハンドラといえばUnhandledExceptionですよね。
AppDomain.CurrentDomain.UnhandledException += (s, e) => {};
UnhandledExceptionを使用すれば例外をキャッチできますが、補足することができないためアプリが終了してしまいます。
ならどうするのか、、、
以下の処理を使えばアプリを終了させないようにできるそうです!
AndroidEnvironment.UnhandledExceptionRaiser += (s, e) => { e.Handled = true; };
(Handledをtrueにすることで強制的に補足済みの例外にしています)
実際のコードは以下になります。
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Main); AndroidEnvironment.UnhandledExceptionRaiser += (s, e) => { e.Handled = true; }; }
サンプル
実際に以下のように組み込んでみました。
(今回はボタンクリックでExceptionを発生させ、UnhandledExceptionRaiser内でトーストを表示させています)
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Main); Button button = FindViewById<Button>(Resource.Id.myButton); button.Click += delegate { throw new Exception("EXCEPTION"); }; AndroidEnvironment.UnhandledExceptionRaiser += (s, e) => { Toast.MakeText(this, "例外発生!!", ToastLength.Short).Show(); e.Handled = true; }; }
とりあえず落ちないアプリ?の作成はできました笑
これは使い方次第でありかも?
【iOS 10】User Notifications Frameworkで通知をカスタムしてみる
iOS 10が公開されて1ヶ月が経ちました。
新しいAPIが大量に追加され、Swiftもメジャーアップデートし、色んな意味で楽しい開発ができています。
そして、発売日からちょうど1ヶ月後の、10月16日に予約開始日に予約していたiPhone 7 Plus ジェットブラックが届きました。(被写界深度エフェクトタノチーwwwww)
街なかの広告を見てイライラする日々からついに開放されました。
さて、今回はiOS 10で追加されたUser Notifications Frameworkを紹介します。
User Notifications Framework
これまでiOSでの通知は"Remote Notification"と"Local Notification"が別物として存在していましたが、User Notifications Frameworkではこの2つを統合し、同じフレームワーク内で処理することができます。
そして、アプリ起動中でも通知を表示できるようになったので、別途アプリ内通知を実装する必要がなくなりました。
発生条件
User Notifications Frameworkでは以下の4つのトリガーによって通知を発生します。
・Push
iOS 9までに存在していたRemote Notificationと同等
・Time Interval
一定時間後に通知を発生する
繰り返し可能だが、最短時間が60秒に制限される
・Calendar
日時指定で通知を発生する
DateComponentsに一致すれば繰り返し可能
・Location
位置情報に基づき通知を発生する
カスタム
地図やカレンダーの情報を通知上に表示したり、画像や動画、音声などのメディアを添付することができるようになりました。
Notification Content Extensionを実装することで自由にレイアウトを変更することができます。 通知直後は縮小表示になるので3DTouchに対応している場合は押し込むことで、対応していない場合は下に引き下げることで全体を表示します。
また、キーボードからの入力も行えるのでメッセンジャーアプリなどでアプリを起動することなく返信することができるようになります。
サンプル
今回は、Pushを除いたトリガーでの通知発生と画像の添付、アクションの追加までのサンプルを作成してみました。
まずは、通知を許可するようにユーザに求めるダイアログを表示します。
AppDelegateを以下のように編集します
import UserNotifications class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // 通知の許可をリクエスト let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.badge, .sound, .alert], completionHandler: { (granted, error) in if error != nil { return } if granted { debugPrint("通知許可") let center = UNUserNotificationCenter.current() center.delegate = self } else { debugPrint("通知拒否") } }) return true } }
次に通知を行いたい場所で以下の処理を行います。
トリガーの設定
5秒後に通知する場合
let trigger: UNNotificationTrigger trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
60秒毎通知する場合
let trigger: UNNotificationTrigger trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
日時指定で通知する場合 (現在時間から1分後に設定)
let trigger: UNNotificationTrigger var dateComponents = DateComponents() dateComponents.minute = dateComponents.minute! + 1 trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
位置情報によって通知する場合
let trigger: UNNotificationTrigger let coordinate = CLLocationCoordinate2DMake(35.170915, 136.8793482) let region = CLCircularRegion(center: coordinate, radius: 100.0, identifier: "description") trigger = UNLocationNotificationTrigger(region: region, repeats: false)
表示の設定
通常
let content = UNMutableNotificationContent() content.title = "タイトル" content.body = "ボディ" content.sound = UNNotificationSound.default() // 通常 let request = UNNotificationRequest(identifier: "normal", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
画像を表示
let content = UNMutableNotificationContent() content.title = "タイトル" content.body = "ボディ" content.sound = UNNotificationSound.default() if let url = Bundle.main.url(forResource: "image", withExtension: "png") { let attachment = try? UNNotificationAttachment(identifier: "attachment", url: url, options: nil) if let attachment = attachment { content.attachments = [attachment] } // categoryIdentifierを設定 content.categoryIdentifier = "attachment" } let request = UNNotificationRequest(identifier: "attachment", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
アクション
UNNotificationCategoryに設定している"repry"と"cancel"はハンドリングの際に処理を分けるために使用します。
let content = UNMutableNotificationContent() content.title = "タイトル" content.body = "ボディ" content.sound = UNNotificationSound.default() let repry = UNNotificationAction(identifier: NotificationActionID.repry.rawValue, title: "返信", options: []) let cancel = UNNotificationAction(identifier: NotificationActionID.cancel.rawValue, title: "キャンセル", options: []) let category = UNNotificationCategory(identifier: "message", actions: [repry, cancel], intentIdentifiers: [], options: []) UNUserNotificationCenter.current().setNotificationCategories([category]) // categoryIdentifierを設定 content.categoryIdentifier = "message" let request = UNNotificationRequest(identifier: "message", content: content, trigger: trigger) // 通知をセット UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
通知のハンドリング
通知を受け取る際はAppdelegateへUNUserNotificationCenterDelegateを実装します
/// 通知表示前のデリゲート /// /// - parameter center: NotificationCenter /// - parameter notification: Notification /// - parameter completionHandler: Handler private func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) { let identifier = notification.request.identifier switch identifier { case "alert": completionHandler([.alert]) // 通知のみ行う case "both": completionHandler([.sound, .alert]) // サウンドと通知 default: () } }
通知設定時のアクションに対応する動作を行う場合は以下のようにします。
アクションに対してNotificationActionIDを設定し、デリゲート内で分岐します。
public enum NotificationActionID: String { case repry case cancel } /// 通知開封時のデリゲート /// /// - parameter center: NotificationCenter /// - parameter response: Notification /// - parameter completionHandler: Handler private func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) { switch response.actionIdentifier { case NotificationActionID.repry.rawValue: /* 返信処理 */ case NotificationActionID.cancel.rawValue: /* キャンセル処理 */ default: () } debugPrint("opened") completionHandler() }
PHPの関数集(日付関連)
今回はPHPで日付を出力する際によく使うと思われる関数のサンプルを紹介していきたいと思います。
現在日時を取得する
現在日時はdate関数を使用します。date関数にフォーマットを指定することで指定したフォーマットの日時を取得することができます。
PHPのdate関数で日時を取得してもミリ秒までは取得できません。ミリ秒まで出力したい場合はstrtotime関数を使用します。
function getNowDateTime() { return date("Y-m-d H:i:s"); } function getNowDateTimeMicro() { return date("Y-m-d H:i:s") . "." . substr(explode(".", (microtime(true) . ""))[1], 0, 3); }
指定した月の月初、月末日を取得する。
PHPの場合、strtotime関数の書式指定で簡単に取得することができます。
modify関数へ引数の日付が変数展開されるよう記述しておきます。
function getFirstDate($targetDate) { $d = new DateTime($targetDate); $d->modify("first day of $targetDate"); return $d->format('Y-m-d H:i:s'); } function getLastDate($targetDate) { $d = new DateTime($targetDate); $d->modify("last day of $targetDate"); return $d->format('Y-m-d H:i:s'); }
次月の月初、月末を取得する。
次月を求めるためにmodify関数へ引数の日付を変数展開されるよう記述しておきます。
function getFirstDateNextMonth($targetDate) { $d = new DateTime($targetDate); $d->modify("first day of $targetDate next month"); return $d->format('Y-m-d H:i:s'); } function getLastDateNextMonth($targetDate) { $d = new DateTime($targetDate); $d->modify("last day of $targetDate next month"); return $d->format('Y-m-d H:i:s'); }
参考
http://php.net/manual/ja/function.date.phpphp.netPHPリファレンス date関数
http://php.net/manual/ja/function.microtime.phpphp.netPHPリファレンス microtime関数
http://php.net/manual/ja/function.strtotime.phpphp.netPHPリファレンス strtotime関数
マルチウィンドウ
さてさて、先日「AndroidN」が正式リリースされました。
AndroidMからの大きな変更点としては
- マルチウィンドウ
- データセーバー
- 通知
などでしょうか。
新機能・変更点などは色々なサイトがまとめてくれているので割愛します。
http://mobilelaby.com/blog-entry-android-n-new-feature.html
http://androidlover.net/android-os/android-m/android-m-surely-releases-2015.html
様々な変更がありますが、その中で今回はマルチウィンドウの対応方法について書いていきたいと思います。
マルチウィンドウとは
マルチウィンドウとは1画面上に複数のアプリを同時に表示すること
では、AndroidNならどんなアプリでもマルチウィンドウにできるのか?
答えは×です。
簡単な手順ですが、対応しなければいけないことがあります。
アプリをマルチウィンドウに適用する
アプリでマルチウィンドウモードを可能にするためには、
<application>
全体、または適用させたい個々の<activity>
のマニフェストファイルで、
新たな属性android:resizeableActivityをtrueに設定する必要があります。
(アプリのtargetSdkVersionがandroidNより以前の場合、属性はデフォルトでfalseになっています)
簡単ですね!!
マルチウィンドウに対応できたら、以下の属性でリサイズの設定をすることができます。
android:defaultWidth:デフォルトの幅を指定 android:defaultHeight:デフォルトの高さを指定 android:gravity:グラビティの初期値。アプリをどこで分割すればよいかを指定 android:minimumSize:最小サイズを指定
マニフェストを修正して、サイズを決めるだけで対応できる。
素晴らしいですね!
と思っていることでしょう。
実はこのマルチウィンドウ、一つ罠が仕掛けられています。
マルチウィンドウに対応しないのであれば、resizeableActivityをfalseにすれば、確かにマルチウィンドウにはならないです。
が、
startActivityForResultで別アプリから呼び出された場合は話は別です。
Activityのマルチウィンドウ設定をfalseにしていても、共有の場合は強制でマルチウィンドウモードになってしまいます。
【参考サイト】
Pro-tip 5: Activities started by other apps must always support multi-window
ということで、暗黙的インテントを作成する場合はマルチウィンドウに対応しておきましょう!
【iOS 10】SiriKit触ってみた
さて、iOS 10から追加されたSiriKitを使うことで、Siriからアプリの機能を使うことができるようになります。 今回はSiriからの機能を使い、メッセージを送るためのサンプルを紹介します。
公式のサンプルや執筆時点でネット上に存在する情報を元に書いているので、動作に問題があるかもしれませんが、とりあえずSiriからの呼び出しが成功したので、手順を紹介します。
環境
・Xcode Version 8.0 beta 6
・iOS 10 beta 8
プロジェクト設定
まず、アプリに対して、Siriの使用を有効にします。 プロジェクトファイルを開き、[Target]からアプリ本体を選択します。 Capabilityタブを開き、SiriをONにして下さい。
次に、Siriから呼ばれるハンドラを作成します。 [File]→[New]→[Target]を選択
iOSタブから[Intents Extension]を選択します。 任意の名前をつけ、プロジェクトにターゲットを追加します。
次に、追加したターゲットのinfo.pristファイルを開き、[NSExtension]→[NSExtensionAttributes]→[IntentsSupported]の中身をINSendMessageIntentのみにします。
コード
Intents ExtensionのIntentHandler.swiftを編集します。
import Intents class IntentHandler: INExtension, INSendMessageIntentHandling, INSearchForMessagesIntentHandling, INSetMessageAttributeIntentHandling { override func handler(for intent: INIntent) -> Any { return self } // MARK:- 解決フェーズ // 宛先の選択時にコールされる func resolveRecipients(forSendMessage intent: INSendMessageIntent, with completion: @escaping ([INPersonResolutionResult]) -> Void) { NSLog("resolveRecipients : %@", intent.recipients?.description ?? "nil") guard let recipients = intent.recipients , recipients.count > 0 else { completion([INPersonResolutionResult.needsValue()]) return } let results:[INPersonResolutionResult] = recipients.flatMap{ INPersonResolutionResult.success(with: $0)} completion(results) } // 送信テキストの入力時にコールされる func resolveContent(forSendMessage intent: INSendMessageIntent, with completion: @escaping (INStringResolutionResult) -> Void) { NSLog("resolveContent : %@", intent.content ?? "nil") // メッセージ内容は必須なので、指定されていない場合は、needsValue()を設定 let result = intent.content != nil ? INStringResolutionResult.success(with: intent.content!) : INStringResolutionResult.needsValue() completion(result) } // MARK:- 確認フェーズ // 送信の確認時にコールされる func confirm(sendMessage intent: INSendMessageIntent, completion: @escaping (INSendMessageIntentResponse) -> Void) { NSLog("confirm : %@", intent.description) let response = INSendMessageIntentResponse(code: .success, userActivity: nil) completion(response) } // 送信の実行時にコールされる func handle(sendMessage intent: INSendMessageIntent, completion: @escaping (INSendMessageIntentResponse) -> Void) { // Implement your application logic to send a message here. NSLog("sendMessage : %@", intent.content ?? "nil"); let userActivity = NSUserActivity(activityType: NSStringFromClass(INSendMessageIntent.self)) let response = INSendMessageIntentResponse(code: .success, userActivity: userActivity) completion(response) } // MARK:- Handling Intentフェーズ func handle(setMessageAttribute intent: INSetMessageAttributeIntent, completion: @escaping (INSetMessageAttributeIntentResponse) -> Void) { NSLog("handle %@", intent.description) // メッセージ送信処理を追加 let response = INSetMessageAttributeIntentResponse(code: .success, userActivity: nil) completion(response) } func resolveGroupName(forSendMessage intent: INSendMessageIntent, with completion: @escaping (INStringResolutionResult) -> Swift.Void){ NSLog("resolveGroupName %@", intent.groupName ?? "nil") // グループに対して送信する場合 let notRequired = INStringResolutionResult.notRequired() completion(notRequired) } func resolveSenders(forSearchForMessages intent: INSearchForMessagesIntent, with completion: @escaping ([INPersonResolutionResult]) -> Swift.Void){ NSLog("resolveSender %@", intent.senders?[0].displayName ?? "nil") let person = INPerson(personHandle: INPersonHandle(value: "Value", type: .emailAddress), nameComponents: PersonNameComponents(), displayName: "displayName", image: nil, contactIdentifier: nil, customIdentifier: nil) let sender = intent.senders == nil ? INPersonResolutionResult.success(with: person) : INPersonResolutionResult.success(with: intent.senders![0]) completion([sender]) } func resolveServiceName(forSendMessage intent: INSendMessageIntent, with completion: (INStringResolutionResult) -> Void) { NSLog("resolveServiceName %@", intent.description) let notRequired = INStringResolutionResult.notRequired() completion(notRequired) } // Implement handlers for each intent you wish to handle. As an example for messages, you may wish to also handle searchForMessages and setMessageAttributes. // MARK: - INSearchForMessagesIntentHandling func handle(searchForMessages intent: INSearchForMessagesIntent, completion: @escaping (INSearchForMessagesIntentResponse) -> Void) { // Implement your application logic to find a message that matches the information in the intent. let userActivity = NSUserActivity(activityType: NSStringFromClass(INSearchForMessagesIntent.self)) let response = INSearchForMessagesIntentResponse(code: .success, userActivity: userActivity) // Initialize with found message's attributes response.messages = [INMessage( identifier: "identifier", content: "I am so excited about SiriKit!", dateSent: Date(), sender: INPerson(personHandle: INPersonHandle(value: "sarah@example.com", type: .emailAddress), nameComponents: nil, displayName: "Sarah", image: nil, contactIdentifier: nil, customIdentifier: nil), recipients: [INPerson(personHandle: INPersonHandle(value: "+1-415-555-5555", type: .phoneNumber), nameComponents: nil, displayName: "John", image: nil, contactIdentifier: nil, customIdentifier: nil)] )] completion(response) } }
実行
実際にSiriから呼び出してみましょう。
「アプリ名 + メッセージを送って」と言うと呼び出してくれます。
はじめは Siri Test というアプリ名を設定していたのですが、 Siri自身へのメッセージと勘違いをされ、「はい、なんでしょう?」のように応答されたので、混同しにくい適当な名前にしましょう。
今回は「はなこ」というアプリ名にしました。
Zend Frameworkでプロジェクトの雛形作成
個人でPHPを利用してWebサイトを作りたい、他にはあまり無いですが仕事でPHPを利用してサイトを構築しなければならない、という事もあるかもしれません。今回はPHPの代表的なFrameworkのZend FrameworkでCLIツールを使用してサイトの雛形を作成する手順を説明します。
framework.zend.comCLIツールの使用 - Zend_Tool_Framework
サイトの雛形作成にはZend FrameworkのZendToolを使って作成します。使用できるコマンドは以下を参考にしてください。
ZFコマンド一覧
コマンド | 説明 |
---|---|
zf show version | Zend Frameworkのバージョンを表示します。 |
zf show phpinfo | phpinfoを表示します。 |
zf show manifest | manifestを表示します。 |
zf show profile | profileを表示します。 |
zf create project [作成するパス] | Zendのプロジェクトを作成します。パスを指定しない場合は作成するパスの問い合わせが表示されます。 |
zf show project | プロジェクトを表示します。 |
zf create controller [コントローラ名] | Zend Frameworkのcontrollerを作成します。コントローラ名を指定しない場合は作成するコントローラ名の問い合わせが表示されます。 |
zf create action [アクション名] | Zend Frameworkのactionを作成します。アクション名を指定しない場合は作成するアクション名の問い合わせが表示されます。 |
zf create view [コントローラ名] [アクション名] | Zend Frameworkのviewを作成します。コントローラ名とアクション名を指定しない場合は作成するコントローラ名とアクション名の問い合わせが表示されます。 |
zf create module [モジュール名] | Zend Frameworkのmoduleを作成します。モジュール名を指定しない場合は作成するモジュール名の問い合わせが表示されます。 |
では実際にサイトの雛形を作成してみましょう。ZFコマンドはcreate projectを使用します。プロジェクト名は「hoge」で作成を行います。
$ zf create project hoge
作成されたプロジェクトの構成は以下を参考にしてください。これで雛形が作成されました。雛形ではデフォルトコントローラのIndexコントローラのみ作成されていますので、ControllerとViewを追加して実装することになります。
hoge |-- application | |-- Bootstrap.php | |-- configs | | `-- application.ini | |-- controllers | | |-- ErrorController.php | | `-- IndexController.php | |-- models | `-- views | |-- helpers | `-- scripts | |-- error | | `-- error.phtml | `-- index | `-- index.phtml |-- library |-- public | |-- .htaccess | `-- index.php `-- tests |-- application | `-- bootstrap.php |-- library | `-- bootstrap.php `-- phpunit.xml
index.phtmlにスタートページのタグを書き込み、配置すれば簡単なWebサイトの完成です。業務アプリであればIndexController.phpで認証処理を行い認証がNGの場合、ログイン処理を行ってからコントローラへのリダイレクトを行うなどの実装が必要になると思います。
framework.zend.comプロジェクトを作成 - Zend Framework Quick Start
これでプロジェクトの雛形作成の解説は終わりです。Zend Frameworkはリファレンスドキュメントが充実しており公式サイトで事細かに解説がなされています。PHP初心者でも作成はしやすいと思いますので、チャレンジしてみてはいかがでしょうか。
Androidでタップの制御
アプリ開発をしているとほぼ必ず行うタップの制御。
今回はこのタップ制御を使いやすくしてみようと思います。
とりあえず普通に作っていくと、以下のようになると思います。
private boolean isTap = false; Button button = new Button(getApplication()); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(isTap) return; isTap = true; [何かしらの処理] isTap = false; } });
これでも特に問題はないのですが、ボタンが複数ある場合にはそれぞれに処理を書かないといけないですし、フラグの管理を間違えたらボタンが反応しなくなってしまうなどのバグが出てしまいます。
そんな問題を少しでも解消するために少し一工夫をしてみましょう。
まずはベースとなるActivity、もしくはFragmentを作成します。
そして、自動解除用のHandlerとRunnable、タップ管理用のMapを用意します。
public class BaseFragment extends Fragment{ // 自動解除用Handler private Handler handler = new Handler(); // 遅延実行のためのRunnable private Runnable runnable = null; // タップ管理用Map private Map<String, Boolean> map = new HashMap(); }
Activity、FragmentのonPauseでフラグの解除を行っておきます。
@Override public void onPause() { super.onPause(); map.clear(); if (null != runnable) { handler.removeCallbacks(runnable); } }
次にタップ管理の処理を書いていきます。
// タップ制御開始 protected void executeEvent(String key) { map.put(key, true); } // タップ制御開始(自動解除) protected void executeEvent(String key, long delay) { map.put(key, true); runnable = new Runnable() { @Override public void run() { finishEvent(key); } }; handler.postDelayed(runnable, delay); } // タップ制御中かどうか protected boolean isEvent(String key) { return map.containkey(key); } // タップの制御解除 protected void finishEvent(String key) { map.remove(key); }
ベースクラスを継承したActivity, Fragmentであれば以下のように使用することができます。
// 手動解除 Button button = new Button(context); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(isEvent("blockKey")) return; executeEvent("blockKey"); [何かしらの処理] finishEvent("blockKey"); } }); // 自動解除 Button button = new Button(context); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(isEvent("blockKey")) return; executeEvent("blockKey", 1000); // 1秒後に自動解除 [何かしらの処理] } });
単純なタップ制御なら、自動解除が結構使いやすくて便利だと思います。
タップの管理はMapで行っているので、複数ボタン別々のイベントも簡単に実装できます!
以上、タップ制御でした!
【iOS 10】Speech Frameworkで音声認識
先月行われたWWDCでiOS 10が発表され、DeveloperにはすでにiOS 10とXcode 8のベータ版が配布されています。
今回は、iOS 10で実装されたSpeech Frameworkを紹介します。
Speech Frameworkとは
iOS 10から対応するAppleが純正のAPIとして公開した音声認識Frameworkです。
今までiOSで音声認識を使う場合、サードパーティの音声認識ライブラリを使う必要がありましたが、今後はSpeech Frameworkを利用することで、サードパーティに頼る必要がなくなります。
公式のサンプルコード
Using Speech Recognition with AVAudioEngineというサンプルコードがAppleから公開されています。
プロジェクトファイルを開くためにはXcode 8が必要になります。
使い方
音声認識を行うためには"SFSpeechRecognizer"というクラスを使うようです。
初期化の引数としてLocaleクラスを渡します。
// 識別言語を日本語とする private let speechRecognizer = SFSpeechRecognizer(locale: Locale(localeIdentifier: "ja_JP"))!
続いて、Delegateを設定します。
speechRecognizer.delegate = self
Delegateメソッドは以下のものが存在し、Recognizerのステータスが変化した場合に呼び出されるようです。
availableにRecognizerが使用可能か否かの値が入っています。
optional public func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool)
音声認識を使用する場合は権限の許可を得なければならないので、
SFSpeechRecognizerクラスのrequestAuthorizationメソッドで、権限を求めるアラートを表示します。
サンプルでは、許可されている場合に認識を開始するボタンを有効にする処理になっていました。
SFSpeechRecognizer.requestAuthorization { authStatus in // 音声アクセス許可を求める OperationQueue.main().addOperation { switch authStatus { case .authorized: // 許可 case .denied: // 拒否 case .restricted: // 設定などにより制限されている case .notDetermined: // 未認証 } } }
音声入力を使う場合
認識リクエスト
// プロパティで宣言する private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest? // 初期化 recognitionRequest = SFSpeechAudioBufferRecognitionRequest() guard let recognitionRequest = recognitionRequest else { fatalError("Unable to created a SFSpeechAudioBufferRecognitionRequest object") } // 確定前の結果を取得する recognitionRequest.shouldReportPartialResults = true
音声ファイルを使う場合
// プロパティなどで宣言 private var recognitionRequest: SFSpeechURLRecognitionRequest? // 初期化 // URL recognitionRequest = SFSpeechURLRecognitionRequest(url: URL(string: "http://xxxxxxxxxxxxxxxx")!) // ローカルファイル recognitionRequest = SFSpeechURLRecognitionRequest(url: URL(fileURLWithPath: localPath))
タスクの設定
タスクを設定し、値を受け取った場合の処理をBlockで渡します。
// プロパティなどで宣言 private var recognitionTask: SFSpeechRecognitionTask? // タスクを設定 recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest) { result, error in if let result = result { // 結果を取得できた場合の処理 } if error != nil { // 取得エラー } }
resultはSFSpeechRecognitionResultオブジェクトになっています。
// 認識したテキストの取得 result.bestTranscription.formattedString // 終了検知 result.isFinal
音声ファイルを使用する場合は以上で終了です。
認識の開始
AVAudioEngineによりマイクからの音声入力を取得します。
// プロパティなどで宣言 private let audioEngine = AVAudioEngine() // 初期化 audioEngine = AVAudioEngine() guard let inputNode = audioEngine.inputNode else { fatalError("Audio engine has no input node") } // 音声取得形式を設定 let recordingFormat = inputNode.outputFormat(forBus: 0) // 音声入力を受け取った際に、SFAudioBufferRecognitionRequestに受け取ったバッファを追加します。 inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in self.recognitionRequest?.append(buffer) } // 音声の取得を開始します audioEngine.prepare() try audioEngine.start()
注意点
上記のコードで簡単に実装できるSpeech Frameworkですが、いくつか問題点があるようです。 調べて分かった問題点を幾つか紹介します。
・インターネット環境必須
・回数制限あり
・連続使用は1分まで
使ってみて
実際にiPhoneに向かって喋ってみましたが、かなり高い精度で認識してくれているようです。 50文字程度の文章を音読してみましたが、誤字などは無く、識別率100%となりました。
PHPのよくある質問集
WEB構築用の言語としてはやや下火になってきた感がありますが、PHPのよくある質問をまとめてみました。
質問:if文の条件に「==」と「===」って使えるけどこれ何なの…。
回答:「==」は型までは比較しない比較演算子です。「===」の場合は型まで厳密にチェックします。「==」は内部で型の変換が行われるので遅くなります。速度面で速くなる「===」を使いましょう。
例: $a = 1; if ($a == ‘1’) { // 一致 } if ($a === ‘1’) { // 一致しない }
質問:文字列を定義するときに「’」と「”」の2通りあるけどこれ何なの…。
回答:「’」で定義したときは変数の展開はされません。「”」で定義したときは変数が展開されます。変数を展開したいときは「”」を、それ以外のときは「’」を使いましょう。変数展開するときに英字と混ざってわかりにくくなるときがあります。その場合「{}」で囲って記述します。
変数展開の例: $name = ‘田中’; echo “わたしは @{name} です”; 出力結果 わたしは 田中 です
質問:for文遅くね?これ何なの…。
回答:PHPのfor文は結構遅いです。あまりよろしくないコードだとcount関数でループの度に値を取得したりする人がいます。このようなダメコードを排除するためにもforeachを使いましょう。
悪い例: $arr = array(1, 2, 3); for ($i = 0; $i < count($arr); i++) { // 処理 } 良い例: $arr = array(1, 2, 3); foreach ($arr as $key => $value) { // 処理 }
質問:foreachだと最初と最後の要素わからなくね?それでもforeach使うの…。
回答:配列ポインタの先頭と最後に移動するreset関数とend関数があります。これを使いましょう。
例: $arr = array(1, 2, 3); // 先頭の要素を取り出す echo reset($arr); // 先頭の要素を取り出す echo end ($arr);
質問:require, require_once, include, include_onceを書きすぎると遅くなってない?気のせいかな…。
回答:気のせいではありません。まずパスの指定が参照パスになっていないか確認しましょう。参照パスで指定したときは、そのファイルが見つかるまでinclude_pathを探しにいきます。その結果無駄なコストが発生しているのです。 require, require_once, include, include_onceは絶対パスで記述をしましょう。
例: 悪い例: require_once ‘PEAR.php’ 良い例: require_once ‘/usr/share/pear/PEAR.php’
質問:PHPってメソッドのオーバーロード書けなくね?これ何なの…。
回答:PHPではオーバーロードはサポートされていません。その代わりに引数を省略可能とする引数のデフォルト値を定義することができますので、こちらを使用しましょう。またPHP5.6以降を使用するのでしたら可変長引数リストを使用することもできます。
引数のデフォルト値の例: function hoge($arg = null) { if (!is_null(@arg)) { // 処理 } } 可変長引数リストの例: function hoge(...$args) { foreach ($args as $arg) { // 処理 } }
質問:PHPでも春分、秋分の日って日付型で計算できるの?
回答:PHPでも一般に公開されている計算式で算出できます。以下が春分、秋分の日付を計算するサンプルとなります。
/** * 春分日を算出します。 * @param int $year 算出対象となる年 * @return DateTime 春分日 */ public function CalcVernalEquinoxDay(@year) { // 2000年の太陽の春分点通過日 @baseDate = 20.69115; // 春分点通過日の移動量 = (西暦年 - 2000年) * 0.242194 @movement = (@year - 2000) * 0.242194; // 閏年によるリセット量 = (int)((西暦年 - 2000年) / 4) @leapYearOffset = (int)((@year - 2000) / 4.0); // 春分日 = (int)((1)+ (2) - (3)) @vernalEquinoxDay = (int)(@baseDate + @movement - @leapYearOffset); $date = new DateTime(); return $date->setDate(@year, 3, @vernalEquinoxDay); } /** * 秋分日を算出します。 * @param int $year 算出対象となる年 * @return DateTime 秋分日 */ public function CalcAutumnalEquinoxDay(@year) { // 2000年の太陽の秋分点通過日 @baseDate = 23.09; // 秋分点通過日の移動量 = (西暦年 - 2000年) * 0.242194 @movement = (@year - 2000) * 0.242194; // 閏年によるリセット量 = (int)((西暦年 - 2000年) / 4) @leapYearOffset = (int)((@year - 2000) / 4.0); // 秋分日 = (int)((1)+ (2) - (3)) @autumnalEquinoxDay = (int)(@baseDate + @movement - @leapYearOffset); $date = new DateTime(); return $date->setDate(@year, 9, @autumnalEquinoxDay); }