简体   繁体   English

如何将图像设置为UIView的背景但缩放正确?

[英]How to set a image as the background of UIView but scaled properly?

I would like the user to be able to select a image from their photos and set it to the background of the main view. 我希望用户能够从他们的照片中选择一个图像并将其设置为主视图的背景。

This is what I'm currently doing: 这是我目前正在做的:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissModalViewControllerAnimated:YES];

    UIImage *testimg = [info objectForKey:UIImagePickerControllerOriginalImage];

    NSArray  * sysPaths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES );

    filePath = [[NSString alloc] initWithFormat: @"%@/%@", [sysPaths objectAtIndex: 0], @"testimg.png"];
    if ( [UIImagePNGRepresentation ( testimg) writeToFile:filePath atomically:YES] )    ;

    self.backgroundColor= [[UIColor alloc] initWithPatternImage:[[UIImage alloc] initWithContentsOfFile: filePath]];


     }

Aside from this method being a bit sluggish in speed, this works great! 除了这种方法速度稍慢之外,它的效果还不错! There is one problem though. 不过有一个问题。 When the image is selected the image is not scaled properly. 选择图像后,图像无法正确缩放。 How would I get around this? 我该如何解决?

Thanks in advance, 提前致谢,

-David -大卫

Have a look at UIImageView in particular the contentMode property. 看一下UIImageView,特别是contentMode属性。

imageView.contentMode = UIViewContentModeScaleAspectFit; imageView.contentMode = UIViewContentModeScaleAspectFit;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM