phonegap 提供了iOS 设备的基础特性来供html前段页面调用。但是这个也不能满足我们的项目需求,比如 二维码,APNS,截屏等。所以我们就要扩展。
下面我就详细说下phonegap 的插件开发 和 扩展。
在js中要扩展一个方法也很简单。
Native.screenShot = function(options, onSuccess, onFail) {
options = options || {};
var quality = options.quality || 75;
var destinationType = options.destinationType || 0;
var encodingType = options.encodingType || 'JPEG';
var targetWidth = options.targetWidth || -1;
var targetHeight = options.targetHeight || -1;
var saveToPhotoAlbum = options.saveToPhotoAlbum || false;
cordova.exec(onSuccess, onFail, 'Screen', 'screenShot', [quality, //
destinationType, //
encodingType, //
targetWidth, //
targetHeight, //
saveToPhotoAlbum]);
}
上面就是我们对截屏功能的扩展。各个参数具体意思是:
quality: 75, // 图片质量, 1-100(默认为75)
destinationType: 0, // 返回格式, 0:返回base64数据, 1:返回文件uri(默认以base64编码返回)
encodingType: 'PNG', // 图片格式, JPEG或PNG(默认为JPEG)
targetWidth: 640, // 最大分辨率宽度(默认值为-1,表示不限制)
targetHeight: 960, // 最大分辨率高度(默认值为-1,表示不限制)
saveToPhotoAlbum: true // 截屏图片是否保存到相册(默认不保存)
主要还是通过cordova.exec(onSuccess, onFail, 'Screen', 'screenShot', []);
这个函数来执行的。
js 的扩展基本完成了,剩下就是native 这边了。
native这边也很简单,只要我们继续它的一个CDVPlugin类就ok了。
我们新建类CDVScreenShots类。
在config.xml中添加我们的插件CDVScreenShots。
<plugin name="Screen" value="CDVScreenShots" />
啊发发发Screen 是上面js 扩展方面的第三个参数,CDVScreenShots 是我们的native 的 类。上面意思就是 js 的 一个方法映射到本地的某个类。这里就是Screen 映射到本地的CDVScreenShots类。这一步是必须的。
然后在CDV.h中添加
#import "CDVScreenShots.h"
在上面js 扩展方面的第四个参数screenShot,这个其实是对应native 的 一个方法。也就是方面名。所以在CDVScreenShots 类中我们添加
- (void)screenShot:(CDVInvokedUrlCommand*)command;
这个方法。 这样基本就ok了。具体方法是
- (void)screenShot:(CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSString* echo = @"这个是截屏功能";//这个地方是处理的结果,也就是native 的要返回给前端界面的参数, //这个只是举例而已,要安实际情况做处理。
NSLog(@"echo==%@",echo);
if (echo != nil && [echo length] > 0) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
这样就全部ok了。