用代碼改變image的大小

這裏大家可以寫一個image的類別,方便調用,類別如下:

一、.h文件

#import <UIKit/UIKit.h>


@interface UIImage (UIImageExtras)

- (UIImage *)imageByScalingToSize:(CGSize)targetSize; 

@end


二、.m文件

#import "UIImage+UIImageExtras.h"


@implementation UIImage (UIImageExtras)


- (UIImage *)imageByScalingToSize:(CGSize)targetSize

{

   UIImage *sourceImage = self;

   UIImage *newImage = nil;

   CGSize imageSize = sourceImage.size;

   CGFloat width = imageSize.width;

   CGFloat height = imageSize.height;

   CGFloat targetWidth = targetSize.width;

   CGFloat targetHeight = targetSize.height;

   CGFloat scaleFactor = 0.0;

   CGFloat scaledWidth = targetWidth;

   CGFloat scaledHeight = targetHeight;

   CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

   if (CGSizeEqualToSize(imageSize, targetSize) ==NO) {

       CGFloat widthFactor = targetWidth / width;

       CGFloat heightFactor = targetHeight / height;

       if (widthFactor < heightFactor)

            scaleFactor = widthFactor;

       else

            scaleFactor = heightFactor;

        scaledWidth  = width * scaleFactor;

        scaledHeight = height * scaleFactor;

        // center the image

       if (widthFactor < heightFactor) {

            

            thumbnailPoint.y = (targetHeight - scaledHeight) *0.5;

        }else if (widthFactor > heightFactor) {

            thumbnailPoint.x = (targetWidth - scaledWidth) *0.5;

        }

    }

    // this is actually the interesting part:

    UIGraphicsBeginImageContext(targetSize);

   CGRect thumbnailRect = CGRectZero;

    thumbnailRect.origin = thumbnailPoint;

    thumbnailRect.size.width  = scaledWidth;

    thumbnailRect.size.height = scaledHeight;

    [sourceImagedrawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

   if(newImage == nil)

        NSLog(@"could not scale image");

   return newImage ;

}

@end

創建類別的方法:

1.command+n  --> 選擇cocoa Touch裏的Objective-C category --> next --> 類別選擇UIImage,名字隨便起,我的是UIImageExtras之後確定再把上邊的代碼粘貼過去即可。


調用方法:
1.在需要的地方加入頭文件#import "UIImage+UIImageExtras.h" 然後

UIImage * image2 = [image1imageByScalingToSize:CGSizeMake(Width, Height)];

得到的image2的大小即所需大小。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章