本文将介绍Objective-C语言的新物性,类别(categories)允许在现有的类中添加用户自己的方法,有时我们需要在一个已经定义好的类中增加一些方法,而不想去重写该类。比如,当工程已经很大,代码量比较多,或者类中已经包住很多方法,已经有其他代码调用了该类创建对象并使用该类的方法时,可以使用类别对该类扩充新的方法。
类别.h声明文件
#import
@interface
//这个方法就是我添加的图片压缩的方法
- (UIImage*)imageByScalingAndCroppin
@end
类别.m实现文件
#import
@implementation
- (UIImage*)imageByScalingAndCroppin
{
UIImage
UIImage
CGSize
CGFloat
CGFloat
CGFloat
CGFloat
CGFloat
CGFloat
CGFloat
CGPoint
if
{
CGFloat
CGFloat
if
scaleFactor = widthFactor;
else
scaleFactor = heightFactor;
scaledWidth= width * scaleFactor;
scaledHeight = height * scaleFactor;
// center the image
if
{
thumbnailPoint.y
}
else
{
thumbnailPoint.x
}
}
UIGraphicsBeginImageCont
CGRect
thumbnailRect.origin
thumbnailRect.size.width= scaledWidth;
thumbnailRect.size.height
[sourceImage
newImage =
if(newImage ==
NSLog(@"could not scale image");
//pop the context to get back to the default
UIGraphicsEndImageContex
return
}
@end
//根据图片tag显示图片
-(void)showPhotoBySerialNumber:(int)imageTag;
{
//这个largeImageArray是NSMutableArray类型的,存放图片存储路径,根据路径得到UIImage
UIImage
//MyScrollView是我自定义的ScrollView,目的是使ScrollView响应点击事件,关于如何自定义的ScrollView在以后的博客中,我将会阐述
MyScrollView
scrView.host
//这句就是调用了类别,通过UIImage实例对象,调用imageByScalingAndCroppin
scrView.image
scrView.tag
//下面这句,就是把上面的scrView塞到imageScrollView上,imageScrollView是UIScrollView类型
[self.imageScrollView
[scrView
}