//
//ViewController.m
//表情繪畫--作業(yè)(7月21日)
//
#import"ViewController.h"
#import"FaceView.h"
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
@interfaceViewController()
{
UITextField*_text;
FaceView*face;
}
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
face= [[FaceViewalloc]initWithFrame:CGRectMake(0,kScreenHeight-200,kScreenWidth,200)];
[self.viewaddSubview:face];
_text= [[UITextFieldalloc]initWithFrame:CGRectMake(50,kScreenHeight-250,250,50)];
_text.backgroundColor=[UIColorgreenColor];
[self.viewaddSubview:_text];
__weakUITextField*weakText =_text;//防止循環(huán)引用
//構(gòu)建執(zhí)行代碼block为迈,傳遞給消息的發(fā)送者
[faceinitFaceBlock:^(NSString*faceName,UIImage*faceImg) {
//因為weak類型指針變量的特殊性扩劝,所以在使用時油坝,最好將weak類型再次轉(zhuǎn)化為strong類型
__strongUITextField*strongText = weakText;
strongText.text= faceName;
}];
}
@end
//FaceView.h
//表情繪畫--作業(yè)(7月21日)
//
#import
typedefvoid(^FaceBlock)(NSString*,UIImage*);//使用block實現(xiàn)消息傳遞,發(fā)送表情名字蹬挺,和圖片的名字维贺,F(xiàn)aceView發(fā)送者,_text為接受者
@interfaceFaceView :UIView
@property(copy,nonatomic)FaceBlockblock;//_text接受者為發(fā)送者定義的屬性巴帮,發(fā)送者發(fā)送內(nèi)容溯泣,放在此屬性當中虐秋,一定使用copy
-(void)initFaceBlock:(FaceBlock)block;
@end
//
//FaceView.m
//表情繪畫--作業(yè)(7月21日)
//
#import"FaceView.h"
@interfaceFaceView()
{
NSMutableArray *_faceArray;//存儲表情圖片的數(shù)組
CGFloat imgWidth;//表情大小
}
@end
@implementationFaceView
-(instancetype)initWithFrame:(CGRect)frame{
self= [superinitWithFrame:frame];
if(self) {
[selfloadData];
}
returnself;
}
//導(dǎo)入數(shù)據(jù)
-(void)loadData{
//導(dǎo)入路徑
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"face"ofType:@"plist"];
_faceArray = [NSMutableArray arrayWithContentsOfFile:filePath];
}
- (void)drawRect:(CGRect)rect {
imgWidth=self.bounds.size.width/10;//表情的大小
for(inti=0; i<1; i++) {//行
for(intj =0; j<4; j++) {//列
//計算表情的繪制位置和大小
CGRectimgFrame =CGRectMake(j*imgWidth, i*imgWidth,imgWidth,imgWidth);
//將表情繪制到界面中
//CGContextRef context = UIGraphicsGetCurrentContext();
NSDictionary*dic =[_faceArrayobjectAtIndex:i*10+j];
UIImage*img = [UIImageimageNamed:dic[@"jpg"]];
[imgdrawInRect:imgFrame];
}
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{
//獲取手指的位置
UITouch*touch = [touchesanyObject];
CGPointpoint = [touchlocationInView:self];
//計算手指所點的行列
NSIntegerxIndex = point.x/imgWidth;
NSIntegeryIndex = point.y/imgWidth;
NSIntegerindex = xIndex+yIndex*10;
//計算出的下標,獲得表情字典內(nèi)的表情
NSDictionary*dic =_faceArray[index];
NSLog(@"%@",dic[@"chs"]);
UIImage*img = [UIImageimageNamed:dic[@"jpg"]];
//判斷block是否存在
if(_block) {
_block(dic[@"chs"],img);
}
}
//接受者給發(fā)送者的代碼垃沦,發(fā)送者需要發(fā)送消息時客给,執(zhí)行這個block,傳入相應(yīng)的數(shù)據(jù)即可
-(void)initFaceBlock:(FaceBlock)block{
if(_block!= block) {
_block= [blockcopy];
}
}
@end