Objective C - 设置ImageView宽度并保持纵横比

时间:2015-09-13 01:12:16

标签: ios objective-c uiimageview uiimage

我正在使用以下动画在视图上显示缩略图的全屏图像:

[UIView animateWithDuration:0.5 delay:0 options:0 animations:^{

            [testImageView setFrame:CGRectMake(0, 0, testImage.size.width, testImage.size.height)];

        }completion:^(BOOL finished){

}];

但是,如果图像是大图像,则不会包含屏幕范围内的图像。

有没有办法可以将图像的宽度设置为屏幕的宽度,然后调整图像的高度,以保持正确的宽高比?

3 个答案:

答案 0 :(得分:1)

CGRect bounds = [UIScreen mainScreen].bounds;
[testImageView setFrame:bounds];
testImageView.contentMode = UIViewContentModeScaleAspectFit;

但是如果图像的比例不等于屏幕,则可能会有一些填充。如果您希望图像覆盖整个屏幕,则将contentMode更改为UIViewContentModeScaleAspectFill。

答案 1 :(得分:1)

与上述方法类似,但稍作修改:

CGFloat verticalScale = image.height / bounds.height;
CGFloat horizontalScale = image.width / bounds.width;
CGFloat scale = max(verticalScale,horizontalScale);
CGFloat imageViewHeight = image.height / scale;
CGFloat imageViewWidth = image.width / scale;
CGRect imageViewFrame = CGRectMake(x: DESIRE_X, y: DESIRE_Y, width:imageViewWidth ,height:imageViewHeight)
imageView.frame = imageViewFrame;
imageView.contentMode = UIViewContentModeScaleAspectFill;

答案 2 :(得分:0)

请尝试以下代码:

     FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

        byte[] fileText = new byte[fs.Length];

        int bytesRead = fs.Read(fileText, 0, fileText.Length);

        Console.WriteLine(Encoding.ASCII.GetString(fileText, 0, bytesRead));