一.  关于监听手机截图

1. 背景: 发现商品的售价页总是被人转发截图,为了方便用户添加截图分享的小功能

首先要注册用户截屏操作的通知

- (void)viewDidLoad {
[super viewDidLoad];
//注册用户的截屏操作通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(userDidTakeScreenshot:)
name:UIApplicationUserDidTakeScreenshotNotification object:nil];
}

之后人为截图

// 截屏响应
- (void)userDidTakeScreenshot:(NSNotification *)notification
{
//人为截屏, 模拟用户截屏行为, 获取所截图片
_screenshotImg = [UIutils imageWithScreenshot]; // 这里封装了一下 获得图片就可以取分享啦
DhshareActionSheetScreenshot *shareAlert = [[DhshareActionSheetScreenshot alloc] init];
[shareAlert showWithImg:_screenshotImg];
}

人为截图,在这里可以对图片进行一些操作,比如添加自己的APP二维码啥的类似微博

/**
* 截取当前屏幕 并修改
*/
+ (UIImage *)imageWithScreenshot
{
CGSize imageSize = CGSizeZero;
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsPortrait(orientation))
imageSize = [UIScreen mainScreen].bounds.size;
else
imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width); UIGraphicsBeginImageContextWithOptions(imageSize, NO, );
CGContextRef context = UIGraphicsGetCurrentContext();
for (UIWindow *window in [[UIApplication sharedApplication] windows])
{
CGContextSaveGState(context);
CGContextTranslateCTM(context, window.center.x, window.center.y);
CGContextConcatCTM(context, window.transform);
CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
if (orientation == UIInterfaceOrientationLandscapeLeft)
{
CGContextRotateCTM(context, M_PI_2);
CGContextTranslateCTM(context, , -imageSize.width);
}else if (orientation == UIInterfaceOrientationLandscapeRight)
{
CGContextRotateCTM(context, -M_PI_2);
CGContextTranslateCTM(context, -imageSize.height, );
} else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
CGContextRotateCTM(context, M_PI);
CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
}
if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
{
[window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
}
else
{
[window.layer renderInContext:context];
}
CGContextRestoreGState(context);
} UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext(); return image;
}

当然最后不要忘记注销通知,这里要注意,根据需求来,如果商品详情页又可以跳转到别的商品详情页最好这样注销,

避免跳到别的商品详情页多次截图

- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationUserDidTakeScreenshotNotification object:nil]; }

二. UIView生成UIImag

UIView生成UIImage 时可以转一下jpg格式,这样图片不会太大具体参数可以百度,屏幕密度我一般采用0.7;

// UIView生成图片
+(UIImage*)convertViewToImage:(UIView*)v{
CGSize s = v.bounds.size;
// 下面方法,第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果,需要传NO,否则传YES。第三个参数就是屏幕密度了
// NSLog(@"[UIScreen mainScreen].scale-%f",[UIScreen mainScreen].scale);
// 3.0 高清图 分享不了 用2.0即可 或者分享的时候压缩图片
UIGraphicsBeginImageContextWithOptions(s, YES, [UIScreen mainScreen].scale);
[v.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext(); NSData * data = UIImageJPEGRepresentation(image, 0.7);
UIImage* imagelast = [UIImage imageWithData:data]; return imagelast;
}

三. UIImage的裁剪

// 图片裁剪
+ (UIImage *)ct_imageFromImage:(UIImage *)image inRect:(CGRect)rect{ //把像 素rect 转化为 点rect(如无转化则按原图像素取部分图片)
CGFloat scale = [UIScreen mainScreen].scale;
CGFloat x= rect.origin.x*scale,y=rect.origin.y*scale,w=rect.size.width*scale,h=rect.size.height*scale;
CGRect dianRect = CGRectMake(x, y, w, h); //截取部分图片并生成新图片
CGImageRef sourceImageRef = [image CGImage];
CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, dianRect);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]; NSData * data = UIImageJPEGRepresentation(newImage, 0.7);
UIImage* imagelast = [UIImage imageWithData:data];
return imagelast;
}

四. UIImage的压缩

分享图片时根据分享的应用不同对图片大小是有限制的,微信是10M,但是qq小一些,

另外小程序分享的话也是有限制的128Kb,当截图裁剪后无法满足时就需要压缩一下

先是密度压缩然后大小压缩,一般都可以解决的

// 图片压缩
+ (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
// Compress by quality
CGFloat compression = 0.7;
//UIImage转换为NSData
NSData *data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength){
return image;
}
CGFloat max = ;
CGFloat min = ;
for (int i = ; i < ; ++i) {
compression = (max + min) / ;
data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength * 0.9) {
min = compression;
} else if (data.length > maxLength) {
max = compression;
} else {
break;
}
}
UIImage *resultImage = [UIImage imageWithData:data];
if (data.length < maxLength){
return resultImage;
}
// Compress by size
NSUInteger lastDataLength = ;
while (data.length > maxLength && data.length != lastDataLength) {
lastDataLength = data.length;
CGFloat ratio = (CGFloat)maxLength / data.length;
CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
(NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
UIGraphicsBeginImageContext(size);
[resultImage drawInRect:CGRectMake(, , size.width, size.height)];
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
data = UIImageJPEGRepresentation(resultImage, compression);
}
return resultImage;
}

这些是最近APP的截图分享,小程序分享的关于图片的总结.希望帮助到需要的人.

iOS 关于监听手机截图,UIView生成UIImage, UIImage裁剪与压缩的总结的更多相关文章

  1. vue 监听手机键盘是否弹出及input是否聚焦成功

    //定义移动端类型 function pageStats() { let u = navigator.userAgent, app = navigator.appVersion; let obj = ...

  2. 用BroadcastReceiver监听手机网络状态变化

    android--解决方案--用BroadcastReceiver监听手机网络状态变化 标签: android网络状态监听方案 2015-01-20 15:23 1294人阅读 评论(3) 收藏 举报 ...

  3. Android监听手机网络变化

    Android监听手机网络变化 手机网络状态发生变化会发送广播,利用广播接收者,监听手机网络变化 效果图 注册广播接收者 <?xml version="1.0" encodi ...

  4. Android初级教程使用服务注册广播接收者监听手机解锁屏变化

    之前第七章广播与服务理论篇写到: 特殊的广播接收者(一般发广播次数频率很高) 安卓中有一些广播接收者,必须使用代码注册,清单文件注册是无效的 屏幕锁屏和解锁 电量改变 今天在这里就回顾一下,且用代码方 ...

  5. 知识点---js监听手机返回键,回到指定界面

    方法一. $(function(){ pushHistory(); window.addEventListener(“popstate”, function(e) { window.location ...

  6. 使用ionic开发时用遇到监听手机返回按钮的问题~

    当时用的是ionic开发一个app,需求是,当按下手机的返回按钮,在指定的页面双击退出,而在其他页面点击一次返回到上个页面: 其实用ionic自带的服务就可以解决:  //双击退出   $ionicP ...

  7. JavaScript监听手机物理返回键的两种解决方法

    JavaScript没有监听物理返回键的API,所以只能使用 popstate 事件监听. 有两个解决办法: 1.返回到指定的页面 pushHistory(); window.addEventList ...

  8. 监听 手机back键和顶部的回退

    // 回退事件,监听 手机back键和顶部的回退 pushHistory(); window.addEventListener("popstate", function(e) { ...

  9. Android之——监听手机开机事件

    转载请注明出处:http://blog.csdn.net/l1028386804/article/details/47028535 本文中,主要通过监听开机广播来达到监听手机开机状态的操作.在Andr ...

随机推荐

  1. Oracle ADDM报告生成和性能分析

    我写的SQL调优专栏:https://blog.csdn.net/u014427391/article/category/8679315 对于局部的,比如某个页面列表sql,我们可以使用Oracle的 ...

  2. Hangfire源码解析-如何实现可扩展IOC的?

    一.官方描述 These projects simplify the integration between Hangfire and your favorite IoC Container. The ...

  3. mongo connections url string 的问题

    摘要 driver 连接Mongo DB的url其实很简单,就是几个变量拼接成一个url,和关系型数据库没什么不同.但是因为mongo有单个instance和replicaSet不同的部署策略,还有m ...

  4. was cached in the local repository, resolution will not be reattempted until the update interval of fintech has elapsed or updates are forced

    今天使用命令mvn compile编译maven项目时提示错误信息,错误信息如下: [ERROR] Failed to execute goal on project <project_name ...

  5. Android项目目录结构模板以及简单说明【简单版】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 概述 开发Android项目的时候,一般都是一边开发一边根据需求创建目录(包.module),那么我呢就根据以往的项目经验,整理出一个比较 ...

  6. LVS(二)NAT模型配置

    NAT配置模式 环境说明 LVS服务器(在eth0:0上设置VIP为:192.168.159.200/24) Eth0:192.168.159.133/24   GW:192.168.159.2 Et ...

  7. Redis集群伸缩

    集群扩容 前提准备,目前集群中一共有6台机器,端口号分别是6381.6382.6383.6384.6385.6386 1) 准备新节点 准备两个新节点,端口号为6387和6388,配置和以前集群配置一 ...

  8. jquery快速入门(一)

    一.jquery加载文档 jquery加载文档(也叫入口函数) $(document).ready(function(){ // 这里写 jQuery 代码... }); 简写方式: $(functi ...

  9. Jetson Nano Developer Kit

    The Jetson Nano Developer Kit is an AI computer for learning and for making. ​ 一个推理框架,用于部署模型到嵌入式设备. ...

  10. AspNetCore 中使用 InentityServer4(2)

    基于上一篇文章 实现对IdnetityServer4 服务的使用 1:添加接口解决方案,并且使接口受认证服务的保护: 首先在解决方案中添加Api项目如下图所示: 在API项目中添加Nuget 引用 如 ...