タッチした場所に画像が浮き上がってくる

忘れてましたが、勉強用に「iPhoneデベロッパーズクックブック」(エリカ・サドゥン著)を
使っているので、ソースもこれがベースになります。

今回はアニメーションで画像が浮き上がったり沈んだりするサンプルですが、タッチしたところに出したくなったので、そのサンプルです。タッチしたところのポイントUIImageViewに渡す方法にちょっと悩みました。CGRectMakeで作って、それをframeに入れるだけ。ソースにするとたいしたことないんだけど。

@interface ToggleView : UIView {
	BOOL isVisible;
	UIImage *img;
	UIImageView *imgView;
}

@end

@implementation ToggleView

-(id)initWithFrame:(CGRect)frame
{
	self = [super initWithFrame:frame];
	
	isVisible = NO;
	img = [UIImage imageNamed:@"test.png"];
	imgView = [[UIImageView alloc] initWithImage:img];
	imgView.userInteractionEnabled=NO;
	[self addSubview:imgView];
	[imgView setAlpha:0.0f];
	[imgView release];
	
	return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	UITouch *touch = [touches anyObject];
	// 押したときだけ反応する
	if ([touch phase] != UITouchPhaseBegan) return;

	//toggle
	isVisible = !isVisible;

	if (isVisible) {
		// 表示する時は、タッチされた場所を中心に表示する
		CGPoint pt = [[touches anyObject] locationInView:self];
		imgView.frame = CGRectMake(pt.x - img.size.width / 2.0f,
                                           pt.y - img.size.height / 2.0f,
				           img.size.width , img.size.height);
	}

	
	CGContextRef context = UIGraphicsGetCurrentContext();
	[UIView	beginAnimations:nil context:context];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView	setAnimationDuration:1.0];
	[imgView setAlpha:(float)isVisible];
	[UIView commitAnimations];
}

-(void)dealloc
{
	[imgView release];
	[super dealloc];
}

@end