iPhoneやiPadのUIWebでタッチイベントを取得する方法ってのは、
結構見つかります!
以下なんかがそうですね!
http://blog.syuhari.jp/archives/2141
http://d.hatena.ne.jp/yuum3/20100714/1279091415
じゃぁタッチイベント取得したら、カスタマイズして手書き機能を
追加して、指でなぞった軌跡をオーバーレイする事できるんじゃないか?
そう思って調べたところ、上記にもある通り、UIWebViewってのは
複雑で謎の多いViewである事で、単純にはいきません。。。
じゃぁどうするか!!!
今日は、その方法を示したいと思います。
まずは画像!
はい!
こんな風に出来ちゃいます!
iPhoneシミュレータでの実行結果です。
答えは簡単!!!
UIWebViewの上に透明なViewをのせれば良いのです!
UIViewから新たにタッチイベントに反応して描画するViewを作ります!
ソースは以下から!
ポイントは16〜20行目!
Viewのバックグラウンド色を透明に設定しています。
ちなみに16行目のopaqueはあまり関係ないみたい;;;
@interface WritableView : UIView {
UIBezierPath* _path;
}
@end
@implementation WritableView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.opaque = YES;
self.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.0f];
self.autoresizesSubviews = YES;
self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.contentMode = UIViewContentModeScaleToFill;
_path = [UIBezierPath bezierPath];
_path.lineCapStyle = kCGLineCapRound;
_path.lineJoinStyle = kCGLineJoinRound;
}
return self;
}
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch* touch = [[event touchesForView:self] anyObject];
CGPoint touchedLocation = [touch locationInView:self];
[_path removeAllPoints];
[_path moveToPoint:touchedLocation];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [[event touchesForView:self] anyObject];
CGPoint movedLocation = [touch locationInView:self];
[_path addLineToPoint:movedLocation];
[self setNeedsDisplay];
}
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
[[UIColor redColor] setStroke];
_path.lineWidth = 5;
[_path stroke];
}
@end
このViewを、UIViewController等で、UIWebViewの上に作ってあげれば
良いのです!
こんな感じ!
writableView = [[WritableView alloc] initWithFrame:frame]; [webView.superview addSubView:writableView];
どうです?
簡単でしょ?
次回はAndroid版を書きます!
