How to set image to UIImage

后端 未结 12 897
小蘑菇
小蘑菇 2020-12-14 06:20

How can I set image to UIImage object. For example:

UIImage *img = [[UIImage alloc] init];
[img setImage:[UIImage imageNamed:@\"anyImageName\"]]         


        
相关标签:
12条回答
  • 2020-12-14 07:00

    There is an error on this line:

    [img setImage:[UIImage imageNamed@"anyImageName"]]; 
    

    It should be:

    [img setImage:[UIImage imageNamed:@"anyImageName"]]; 
    
    0 讨论(0)
  • 2020-12-14 07:02
    UIImage *img = [UIImage imageNamed@"aImageName"];
    
    0 讨论(0)
  • 2020-12-14 07:08

    Try this code to 100% work....

    UIImageView * imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20,100, 80, 80)];
    imageview.image = [UIImage imageNamed:@"myimage.jpg"];
    [self.view  addSubview:imageview];
    
    0 讨论(0)
  • 2020-12-14 07:12

    Like vikingosgundo said, but keep in mind that if you use [UIImage imageNamed:image] then the image is cached and eats away memory. So unless you plan on using the same image in many places, you should load the image, with imageWithContentsOfFile: and imageWithData:

    This will save you significant memory and speeds up your app.

    0 讨论(0)
  • 2020-12-14 07:15

    You can set an Image in UIImage object eiter of the following way:

    1. UIImage *imageObject = [UIImage imageNamed:@"imageFileName"]; but by initializing UIImage Object like this, the image is always stored in cache memory even you make it nil like imageObject=nil;

    Its better to follow this:

    1. NSString *imageFilePath = [[NSBundle mainBundle] pathForResource:@"imageFilename" ofType:@"imageFile_Extension"];

      UIImage *imageObject = [UIImage imageWithContentsOfFile:imageFilePath];
      

    EXAMPLE: NSString *imageFilePath = [[NSBundle mainBundle] pathForResource:@"abc" ofType:@"png"];

    UIImage *imageObject = [UIImage imageWithContentsOfFile:imageFilePath];
    
    0 讨论(0)
  • 2020-12-14 07:16

    You can't alloc UIImage, this is impossible. Proper code with UIImageView allocate:

    UIImageView *_image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"something.png"]] ;
    

    Draw image:

    CGContextDrawImage(context, rect, _image.image.CGImage);
    
    0 讨论(0)
提交回复
热议问题