Code for iPhone app:
+(UIImage *)imageW开发者_高级运维ithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
CGSize sz = CGSizeMake( 200, 20 );
imageView.contentMode = UIViewContentModeScaleAspectFit;
imageView.image = [Class imageWithImage: [UIImage imageNamed:@"image.png"] scaledToSize: sz];
The resized image is centred in imageView, I would like it to be left aligned (preferably top-left). How can I achieve this? Thanks for any help.
If you have set your imageView to have the content mode UIViewContentModeScaleAspectFit
, iOS will fit your image but it will also introduce transparent bars to the left and right if the fit is smaller than your width.
The solution is to let iOS fit the image, then figure out the new width and set the imageView's width with the new width.
CGSize imgSize = contentProvider.image.size;
CGRect frame = contentProviderViewOriginalFrame;
if (imgSize.width > 0 && imgSize.height > 0)
{
double aspectRatio = (imgSize.width * 1.0) / (imgSize.height * 1.0);
CGFloat newWidth = frame.size.height * aspectRatio;
if (newWidth < frame.size.width)
{
frame.size.width = newWidth;
}
}
Change the contentMode to:
imageView.contentMode = UIViewContentModeTopLeft;
精彩评论