UIImage imageNamed: always returns image at 1x

2019-08-06 05:15发布

问题:

This is my code:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self baseInit];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
        [self baseInit];
    }
    return self;
}

- (void)baseInit {
    _selectedImage = [UIImage imageNamed:@"SelectedStar"];
    _deselectedImage = [UIImage imageNamed:@"DeselectedStar"];
    _rating = 6.5f;
    _editable = NO;
    _imageViews = [[NSMutableArray alloc] init];
    _maxRating = 10;
    _minImageSize = CGSizeMake(5, 5);
    _delegate = nil;

    [self setBackgroundColor:[UIColor whiteColor]];
}

- (void)drawRect:(CGRect)rect {
    NSLog(@"Star size: %@", NSStringFromCGSize(_selectedImage.size));
    NSLog(@"Star scale: %f", _selectedImage.scale);      
    ...
}

Now no matter what target OS or device simulator I use, the NSLog gives me:

2015-01-31 16:54:36.709 RatingViewDeveloper[6076:1679432] Star size: {21.5, 20}
2015-01-31 16:54:36.710 RatingViewDeveloper[6076:1679432] Star scale: 2.000000

The files in my images.xcassets are as follows:

  • ImageSet called DeselectedStar with images:
    • DeselectedStar.png
    • DeselectedStar@2x.png
    • DeselectedStar@3x.png

and the same for an ImageSet called SelectedStar.

The size it returns is always the one for the standard size image, never the 2x or even 3x version, and I do not understand why, the scale is 2.0 after all. I have tried cleaning and building again, but the result is always the crappy 1x image.

回答1:

The height and width of the image with always be of the 1x, 2x will automatically adjust itself, the resolution will double but height and width wont change.

Rename and set some other image as DeselectedStar@2x.png and you will see what I am talking about.