涉及较多项目方法,这里贴主要相关代码。
需要自己写iOS和android底层的调用相册方法并保存到手机可写目录,然后返回到js组件可写目录截图文件的地址,然后通过本文上面的方法进行图片精灵的初始化和显示。需要注意的是,iOS和android被js调用的方法均需要时静态方法。
js方法:
// 打开原生相册获取头像图片
showImagePicker: function(){
let ret = false;
// 调用android AppController类showImagePicker方法打开原生相册获取头像图片
if(cc.sys.os === cc.sys.OS_ANDROID){
ret = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/ImagePicker", "openPhoto", "(IIII)Z", this.imgPurpose, this.imgShape, this.imgWidth, this.imgHeight);
}
// 调用iOS AppController类showImagePicker方法打开原生相册获取头像图片
else if(cc.sys.os === cc.sys.OS_IOS){
ret = jsb.reflection.callStaticMethod("AppController", "showImagePicker:imgShape:imgWidth:imgHeight:", this.imgPurpose, this.imgShape, this.imgWidth, this.imgHeight);
}
},
// C++/java更换头像回调函数
// picPath:从相册获取的头像保存地址
window.cropPicturesCallback = function(imgPurpose, picPath){
G.selectImage = picPath;
}
然后是客户端iOS或java代码,这个网上有很多,你可以搜一下,比如iOS的相册打开方法:
#import <UIKit/UIKit.h>
#import “cocos2d.h”
#import “AppController.h”
#import “AppDelegate.h”
#import “RootViewController.h”
#import “platform/ios/CCEAGLView-ios.h”
#import “ScriptingCore.h”
//#import “UIImage+XG.h”
#import “GKImagePicker.h”
#import “UIImage+CircleImage.h”
#import “RootViewController.h”
#import “Reachability.h”
@implementation AppController
#pragma mark -
#pragma mark Application lifecycle
//@synthesize imagePicker;
static NSInteger imgPurpose;
static NSInteger imgShape;
static NSInteger imgWidth;
static NSInteger imgHeight;
NSString *networkStatus;
+(bool) isFileExist:(NSString *) fileUrl
{
// NSLog(@“isFileExist------------: %@”, fileUrl);
if(NULL != fileUrl){
std::string strFileUrl = [fileUrl UTF8String];
std::string imgPath = strFileUrl;
FILE *fp = fopen(imgPath.c_str(),“r”);
if(fp != NULL)
{
fclose(fp);
return true;
}
else{
return false;
}
}
else{
return false;
}
}
//打开相册
static GKImagePicker imagePicker;
+(bool) showImagePicker:(NSNumber)purpose imgShape:(NSNumber*)shape imgWidth:(NSNumber*)width imgHeight:(NSNumber*)height
{
imgPurpose = [purpose integerValue];
imgShape = [shape integerValue];
imgWidth = [height integerValue];
imgHeight = [width integerValue];
// NSLog(@“imgWidth------------: %ld”, (long)imgWidth);
// NSLog(@“imgHeight------------: %ld”, (long)imgHeight);
// iPad使用GKImagePicker库裁剪
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
imagePicker = [[GKImagePicker alloc] init];
imagePicker.cropSize = CGSizeMake(imgWidth, imgHeight);
imagePicker.delegate = self;
imagePicker.resizeableCropArea = YES;
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:imagePicker.imagePickerController animated:YES completion:nil];
}
// iphone使用iOS原生库裁剪
else{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.allowsEditing = true;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:imagePicker animated:YES completion:nil];
}
return YES;
}
// GKImagePicker库回调函数
+(void)imagePicker:(GKImagePicker *)imagePicker pickedImage:(UIImage *)image{
[self saveImage:image];
[self hideImagePicker];
}
+(void)hideImagePicker{
[imagePicker.imagePickerController dismissViewControllerAnimated:YES completion:nil];
}
-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
return UIInterfaceOrientationMaskAll;
}
else {
return UIInterfaceOrientationMaskAllButUpsideDown;
}
}
//选取照片完成
+(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@“public.image”]) {
UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
[self saveImage:img];
} else {
}
[picker dismissViewControllerAnimated:YES completion:nil];
}
// 取消选择
+(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:nil];
}
//保存图片
+(void)saveImage:(UIImage *)img
{
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* uuid = [[NSUUID UUID] UUIDString];
NSString* fileName;
fileName = [uuid stringByAppendingFormat:@".png"];
std::string strFileName = [fileName UTF8String];
NSString *imgFilePath = [documentsDirectory stringByAppendingPathComponent: fileName];
success = [fileManager fileExistsAtPath:imgFilePath];
std::string newImgPath = cocos2d::FileUtils::getInstance()->getWritablePath() + strFileName;
if (success) {
success = [fileManager removeItemAtPath:[NSString stringWithFormat:@"%s",newImgPath.c_str()] error:&error];
}
// 按参数裁剪 0方形 1圆形
UIImage * smallImage;
//裁剪圆形
if(imgShape == 1){
// UIImage * smallImage = [UIImage imageWithIconName:img borderImage:img border:0]; //备用方法 UIImage+XG
img = [UIImage clipCircleImageWithName:img size:CGSizeMake(imgWidth, imgHeight) borberWidth:0 borberColor:[UIColor blueColor]];
}
// 缩略图生成
smallImage = [self thumbnailWithImageWithoutScale:img size:CGSizeMake(imgWidth, imgHeight)];
// UIImagePNGRepresentation UIImageJPEGRepresentation
[UIImagePNGRepresentation(smallImage) writeToFile:[NSString stringWithFormat:@"%s",newImgPath.c_str()] atomically:YES];
NSString * purpose = [NSString stringWithFormat:@"%ld",(long)imgPurpose];
std::string strImgPurpose = [purpose UTF8String];
// 新的照片地址回调给js
std::string funName = “cropPicturesCallback”;
std::string rStr = funName + “(”" + strImgPurpose + “”,"" + newImgPath + “”);";
ScriptingCore::getInstance()->evalString(rStr.c_str());
// NSLog(@“newImgPath----------:%@”, imgFilePath);
}
// 实现缩略图
+(UIImage *) thumbnailWithImageWithoutScale:(UIImage *)img size:(CGSize)asize
{
UIImage * newImg;
if (nil == img) {
newImg = nil;
}else {
CGSize oldsize = img.size;
CGRect rect;
if(asize.width/asize.height > oldsize.width/oldsize.height){
rect.size.width = asize.height * oldsize.width / oldsize.height;
rect.size.height = asize.width;
rect.origin.x = (asize.width - rect.size.width) / 2;
rect.origin.y = 0;
}else{
rect.size.width = asize.width;
rect.size.height = asize.width * oldsize.height / oldsize.width;
rect.origin.x = 0;
rect.origin.y = (asize.height - rect.size.height) / 2;
}
UIGraphicsBeginImageContext(asize);
CGContextRef content = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(content, [[UIColor clearColor] CGColor]);
UIRectFill(CGRectMake(0, 0, asize.width, asize.height));
[img drawInRect:rect];
newImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return newImg;
}