6

画像を uiimageview に合わせようとしています。画像は動的にダウンロードおよびロードされ、ios および android アプリで使用できる解像度は 1 つだけです。

そこで、アスペクト比を維持し、幅に合わせて拡大縮小する画像が必要で、UIImageViewコンテンツモードを UIViewContentModeScaleAspectFillに設定しましたが、画像が中央に配置されるため、上下両方とも画面からはみ出してしまい、画像は下部が不要になるように設計されます。

画像を左上隅に揃えるにはどうすればよいですか?

また、UIImageView も幅に合わせて調整できますか? またはどうすればできますか?

前もって感謝します。

編集:

私が試したところsetcliptobounds、画像がイメージビューのサイズにカットされましたが、それは私の問題ではありません。

UIViewContentModeTopLeftうまく機能していますが、今はUIViewContentModeScaleAspectFill適用できませんか、それとも両方を適用できますか?

4

3 に答える 3

12

画像ビューの幅に合わせて画像を拡大縮小できます。

UIImage選択した幅で新しい画像を作成するカテゴリを使用できます。

@interface UIImage (Scale)

-(UIImage *)scaleToWidth:(CGFloat)width;

@end

@implementation UIImage (Scale)

-(UIImage *)scaleToWidth:(CGFloat)width
{
    UIImage *scaledImage = self;
    if (self.size.width != width) {
        CGFloat height = floorf(self.size.height * (width / self.size.width));
        CGSize size = CGSizeMake(width, height)

        // Create an image context
        UIGraphicsBeginImageContext(size);

        // Draw the scaled image
        [self drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];

        // Create a new image from context
        scaledImage = UIGraphicsGetImageFromCurrentImageContext();

        // Pop the current context from the stack
        UIGraphicsEndImageContext();
    }
    // Return the new scaled image
    return scaledImage;
}

@end

このようにして、それを使用して画像をスケーリングできます

UIImage *scaledImage = [originalImage scaleToWidth:myImageView.frame.size.width];
myImageView.contentMode = UIViewContentModeTopLeft;
myImageView.image = scaledImage;
于 2013-07-22T10:20:48.103 に答える
0

UIImageView で縦横比を揃えて保持することはできませんが、これを可能にする UIImageViewAligned という名前の UIImageView の優れたサブクラスがあります。このプロジェクトは、こちらから github で見つけることができます。
あなたがする必要があるのは次のとおりです:

  1. まず UIImageViewAligned-master/UIImageViewAligned/ からヘッダーと実装をプロジェクトにコピーします
  2. IB のオブジェクト ライブラリから ImageView オブジェクトをビューに挿入します。
  3. [ユーティリティ] ペインの Identity Inspector で、ImageView のクラスを UIImageViewAligned に変更します。
  4. 次に、Identity Inspector の User Defined Runtime Attributes セクションで、必要なアライメントをキーパスとして追加します

それでおしまい。プロジェクトを実行して、それを確認してください。

于 2015-08-03T13:23:08.200 に答える
0

UIViewこれは のスーパークラスでUIImageViewあり、プロパティを持っていますcontentMode。画像の左上揃えには、次の定数を使用できます。

UIViewContentModeTopLeft

Aligns the content in the top-left corner of the view.

アスペクト比を維持するには

UIViewContentModeScaleAspectFit

Scales the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view’s bounds is transparent.
于 2013-07-22T10:08:18.603 に答える