web-dev-qa-db-ja.com

UIButtonの画像をAspectFitに拡大縮小しますか?

画像をUIButtonに追加し、UIButtonに合わせて画像を拡大縮小したい(画像を小さくしたい)。方法を教えてください。

これは私が試したものですが、動作しません:

  • ボタンに画像を追加し、setContentModeを使用:
[self.itemImageButton setImage:stretchImage forState:UIControlStateNormal];
[self.itemImageButton setContentMode:UIViewContentModeScaleAspectFit];
  • 「ストレッチ画像」の作成:
UIImage *stretchImage = [updatedItem.thumbnail stretchableImageWithLeftCapWidth:0 topCapHeight:0];
86
KONG

本当に画像をスケーリングしたい場合は、それを行いますが、使用する前にサイズを変更する必要があります。実行時にサイズを変更すると、CPUサイクルが失われます。

これは、画像をスケーリングするために使用しているカテゴリです:

UIImage + Extra.h

@interface UIImage (Extras)
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
@end;

UIImage + Extra.m

@implementation UIImage (Extras)

- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {

UIImage *sourceImage = self;
UIImage *newImage = nil;

CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;

CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;

CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;

CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

if (!CGSizeEqualToSize(imageSize, targetSize)) {

        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor < heightFactor) 
                scaleFactor = widthFactor;
        else
                scaleFactor = heightFactor;

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image

        if (widthFactor < heightFactor) {
                thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
        } else if (widthFactor > heightFactor) {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
}


// this is actually the interesting part:

UIGraphicsBeginImageContextWithOptions(targetSize, NO, 0);

CGRect thumbnailRect = CGRectZero;
thumbnailRect.Origin = thumbnailPoint;
thumbnailRect.size.width  = scaledWidth;
thumbnailRect.size.height = scaledHeight;

[sourceImage drawInRect:thumbnailRect];

newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

if(newImage == nil) NSLog(@"could not scale image");


return newImage ;
}

@end

必要なサイズに使用できます。好む :

[self.itemImageButton setImage:[stretchImage imageByScalingProportionallyToSize:CGSizeMake(20,20)]];
27
gcamp

同じ問題がありました。 UIButton内にあるImageViewのContentModeを設定するだけです。

[[self.itemImageButton imageView] setContentMode: UIViewContentModeScaleAspectFit];
[self.itemImageButton setImage:[UIImage imageNamed:stretchImage] forState:UIControlStateNormal];

お役に立てれば。

198
Dave

ここでの答えはどれも本当にうまくいきませんでしたが、次のコードで問題を解決しました:

button.contentMode = UIViewContentModeScaleToFill;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;

Interface Builderでもこれを行うことができます。

enter image description here

96
NAlexN

aspect fitモードでUIButton imageViewをプログラムで設定する最も簡単な方法:

スイフト

button.contentHorizontalAlignment = .fill
button.contentVerticalAlignment = .fill
button.imageView?.contentMode = .scaleAspectFit

Objective-C

button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
button.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
button.imageView.contentMode = UIViewContentModeScaleAspectFit;

注:.scaleAspectFit(UIViewContentModeScaleAspectFit)を.scaleAspectFill(UIViewContentModeScaleAspectFill)に変更して、アスペクトフィルモードを設定できます。

47
Tanguy G.

画像が比例的にサイズ変更されないという問題があったため、修正方法はエッジインセットを使用していました。

fooButton.contentEdgeInsets = UIEdgeInsetsMake(10, 15, 10, 15);
19
ninjaneer

Daveの答えを拡張して、ランタイム属性を使用して、コードなしで、ボタンのcontentModeimageViewをすべてIBに設定できます。

enter image description here

  • 1UIViewContentModeScaleAspectFitを意味し、
  • 2UIViewContentModeScaleAspectFillを意味します。
14
Ortwin Gentz

これは、IBのUIButtonプロパティを介して実行できるようになりました。重要なのは、画像を背景として設定することです。そうしないと機能しません。

enter image description here

14
capikaw

ボタンの画像を単に縮小したい場合:

yourButton.contentMode = UIViewContentModeScaleAspectFit;
yourButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
8
Tulleb

最もクリーンなソリューションは、自動レイアウトを使用することです。 UIButtonの-​​コンテンツ圧縮耐性優先度を下げて、Interface Builderで画像を設定します(背景画像ではありません)。その後、ボタンのサイズを定義するいくつかの制約を追加し(私の場合は非常に複雑)、それは魅力のように機能しました。

4

私にはそれを行う方法があります。メソッドはuibuttonを取り、画像のアスペクトを適合させます

-(void)makeImageAspectFitForButton:(UIButton*)button{
    button.imageView.contentMode=UIViewContentModeScaleAspectFit;
    button.contentHorizontalAlignment=UIControlContentHorizontalAlignmentFill;
    button.contentVerticalAlignment=UIControlContentVerticalAlignmentFill;
}
4

画像がImageプロパティに設定されていることを確認してください。背景には設定されていません。

3
andrew

1-ボタンのデフォルトテキストをクリア(重要)

2-画像のような配置を設定します

3-画像のようなコンテンツモードを設定する

enter image description here

3

背景画像は、実際に非常に簡単に縦横比を調整するように設定できます。 UIButtonのサブクラスで次のようなことをするだけです:

- (CGRect)backgroundRectForBounds:(CGRect)bounds
{
    // you'll need the original size of the image, you 
    // can save it from setBackgroundImage:forControlState
    return CGRectFitToFillRect(__original_image_frame_size__, bounds);
}

// Utility function, can be saved elsewhere
CGRect CGRectFitToFillRect( CGRect inRect, CGRect maxRect )
{
    CGFloat origRes = inRect.size.width / inRect.size.height;
    CGFloat newRes = maxRect.size.width / maxRect.size.height;

    CGRect retRect = maxRect;

    if (newRes < origRes)
    {
        retRect.size.width = inRect.size.width * maxRect.size.height / inRect.size.height;
        retRect.Origin.x = roundf((maxRect.size.width - retRect.size.width) / 2);
    }
    else
    {
        retRect.size.height = inRect.size.height * maxRect.size.width / inRect.size.width;
        retRect.Origin.y = roundf((maxRect.size.height - retRect.size.height) / 2);
    }

    return retRect;
}
2
Andy Poes

Xamarin.iOS(C#)の場合:

    myButton.VerticalAlignment = UIControlContentVerticalAlignment.Fill;
    myButton.HorizontalAlignment = UIControlContentHorizontalAlignment.Fill;
    myButton.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
0

Swift 5.0

 myButton2.contentMode = .scaleAspectFit
 myButton2.contentHorizontalAlignment = .fill
 myButton2.contentVerticalAlignment = .fill
0
Qasim Mirza