//
//ViewController.m
//表情绘画--作业(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;//防止循环引用
//构建执行代码block,传递给消息的发送者
[faceinitFaceBlock:^(NSString*faceName,UIImage*faceImg) {
//因为weak类型指针变量的特殊性,所以在使用时,最好将weak类型再次转化为strong类型
__strongUITextField*strongText = weakText;
strongText.text= faceName;
}];
}
@end
//FaceView.h
//表情绘画--作业(7月21日)
//
#import
typedefvoid(^FaceBlock)(NSString*,UIImage*);//使用block实现消息传递,发送表情名字,和图片的名字,FaceView发送者,_text为接受者
@interfaceFaceView :UIView
@property(copy,nonatomic)FaceBlockblock;//_text接受者为发送者定义的属性,发送者发送内容,放在此属性当中,一定使用copy
-(void)initFaceBlock:(FaceBlock)block;
@end
//
//FaceView.m
//表情绘画--作业(7月21日)
//
#import"FaceView.h"
@interfaceFaceView()
{
NSMutableArray *_faceArray;//存储表情图片的数组
CGFloat imgWidth;//表情大小
}
@end
@implementationFaceView
-(instancetype)initWithFrame:(CGRect)frame{
self= [superinitWithFrame:frame];
if(self) {
[selfloadData];
}
returnself;
}
//导入数据
-(void)loadData{
//导入路径
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;
//计算出的下标,获得表情字典内的表情
NSDictionary*dic =_faceArray[index];
NSLog(@"%@",dic[@"chs"]);
UIImage*img = [UIImageimageNamed:dic[@"jpg"]];
//判断block是否存在
if(_block) {
_block(dic[@"chs"],img);
}
}
//接受者给发送者的代码,发送者需要发送消息时,执行这个block,传入相应的数据即可
-(void)initFaceBlock:(FaceBlock)block{
if(_block!= block) {
_block= [blockcopy];
}
}
@end