0

UIImageViewにサブビューとして追加しているの画像の正しい場所を設定するのに問題がありますUIButton。ボタンを作成し、いくつかのサブレイヤーを追加することから始めます。

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:bounds];
//add gradient background
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = button.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[UIColor colorWithRed:.5 green:.5 blue:.5 alpha:1.0].CGColor, (id)[[UIColor blackColor] CGColor], nil];
[button.layer insertSublayer:gradient atIndex:0];

//set green background
CALayer *layer = [CALayer layer];
layer.frame = CGRectInset(button.bounds, 5, 5);
layer.backgroundColor = [UIColor colorWithRed:.55 green:.8 blue:.5 alpha:1.0].CGColor;
[button.layer insertSublayer:layer above:gradient];

次に、2 つの方法を使用して画像を設定します。1 つ目 (画像が保存されていない場合に使用) は、適切なサイズにスケーリングされ、アプリ バンドルの一部である画像リソースを使用します。これを次のコードで設定しました。

UIImageView *v = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"profile.png"]];
[v setBounds:CGRectInset(button.bounds, 8, 8)];
[button addSubview:v];

カメラで撮影してファイルシステムに保存した画像を使用するときに問題が発生します。次のコードを使用して、これをバックグラウンドに設定しています。

//path is an NSString set the the documents location of the image.
UIImageView *v = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:path]];
[v setBounds:CGRectInset(button.bounds, 8, 8)];
[v setContentMode:UIViewContentModeScaleToFill];
[button addSubview:v];

画面への出力は、本来あるべき場所からオフセットされた画像の方法を示しています。

例

私は何を間違っていますか?親ビューで画像を正しく拡大/縮小するにはどうすればよいですか? 単純にボタン画像を設定してみましたが、何も表示されませんでした (画像がサブレイヤーの後ろにあったのでしょうか?)。

4

1 に答える 1

0

-setFrameメソッドを使用して、代わりにイメージビューのフレームを設定しますbounds

[v setFrame:CGRectInset(button.bounds, 8, 8)];

したがって、コードは次のようになります

UIImageView *v = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:path]];
[v setFrame:CGRectInset(button.bounds, 8, 8)];
[v setContentMode:UIViewContentModeScaleToFill];
[button addSubview:v];
于 2013-03-12T16:35:20.813 に答える