需求是连接打印机,将文本内容生成图片然后裁剪之后传输给打印机打印。生成图片之后效果
大概原理是拿到View的上下文的范围,然后根据上下文生成图片
核心代码
/*
self.makeView 视图
self.all 整体获取视图显示ImageView
self.part 裁剪之后图片显示ImageView
*/
//获取上下文范围
UIGraphicsBeginImageContext(self.makeView.bounds.size);
//呈现
[self.makeView.layer renderInContext:UIGraphicsGetCurrentContext()];
//根据当前上下文生成图片
UIImage *allImage = UIGraphicsGetImageFromCurrentImageContext();
CGRect rect = CGRectMake(0, 0, 30, 10);
//根据CGRect裁剪图片
UIImage *partImage = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(allImage.CGImage, rect)];
//释放
UIGraphicsEndImageContext();
self.all.image = allImage;
self.part.image = partImage;