首先获取分享图片。然后分别是android和ios下面的分享
获取分享图片
function gt.getShareImgFile()
local shareimage = gt.getShareImage() --获取一张等待分享的图片(可以是大图)
if cc.FileUtils:getInstance():isFileExist(shareimage) then
local sprite = cc.Sprite:create(shareimage)
sprite:setAnchorPoint(0,0)
sprite:setPosition(0,0)
--head
local playerHead = cc.Sprite:create()
playerHead:setPosition(70,780)
sprite:addChild(playerHead)
gt.playerHeadMgr:attach(playerHead, gt.playerData.uid, gt.playerData.headURL)
-- nick name
local nickName = gt.playerData.nickname
local nickLabel = gt.createTTFLabel(nickName, 28)
nickLabel:enableOutline(cc.c3b(136,43,0),2)
nickLabel:setAnchorPoint(0,0.5)
nickLabel:setPosition(150, 817)
sprite:addChild(nickLabel)
--id
local uidLabel = gt.createTTFLabel("ID:"..gt.playerData.uid, 28)
uidLabel:setColor(cc.c3b(255,246,0))
uidLabel:enableOutline(cc.c3b(136,43,0),2)
uidLabel:setAnchorPoint(0,0.5)
uidLabel:setPosition(150, 777)
sprite:addChild(uidLabel)
local contentSize = sprite:getContentSize()
--set 设置绘制窗口的大小
local view = cc.Director:getInstance():getOpenGLView()
local plicy = view:getResolutionPolicy()
local viewSize = view:getDesignResolutionSize()
view:setDesignResolutionSize(contentSize.width, contentSize.height, plicy)
--截屏
local gl_depth24_stencil8 = 0x88F0
local eFormat = 2
local screenshot = cc.RenderTexture:create(contentSize.width, contentSize.height, eFormat, gl_depth24_stencil8)
screenshot:begin()
sprite:visit()
screenshot:endToLua()
local screenshotFileName = string.format("wx-%s.jpg", os.date("%Y-%m-%d_%H:%M:%S", os.time()))
local shareImgFilePath = cc.FileUtils:getInstance():getWritablePath() .. screenshotFileName
screenshot:saveToFile(screenshotFileName, cc.IMAGE_FORMAT_JPEG, false)
--reset 恢复上面设置的大小
view:setDesignResolutionSize(viewSize.width, viewSize.height, plicy)
return shareImgFilePath
end
end
android下系统分享的实现
/**
* 系统推送部分
* 获取sd卡
*
* @return sd卡路径
*/
public static String getSDPath(){
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
if(sdCardExist)
{
sdDir = Environment.getExternalStorageDirectory();//获取跟目录
}
return sdDir.toString();
}
/**
* 安卓系统分享图片到朋友圈
* @param oldPath mPath 文件路径
* @param newPath desc 文本描述
* @param newPath pName 复制后的文件名称
* @return
*/
private static void shareImgToCircleBySys(String mPath, String desc, String pName) {
String path = getSDPath() + "/" + pName;
copyFile(mPath, path);
File file = new File(path);
if (!file.exists()) {
file.mkdir();
}
Intent intent = new Intent(Intent.ACTION_SEND);
ComponentName comp = new ComponentName("com.tencent.mm",
"com.tencent.mm.ui.tools.ShareToTimeLineUI");
intent.setComponent(comp);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.putExtra("Kdescription", desc);
myContext.startActivity(intent);
}
/**
* 复制单个文件
* @param oldPath String 原文件路径
* @param newPath String 复制后路径
* @return boolean
*/
public static void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
lua层调用:
local imgFullPath = gt.getShareImgFile()
local desc = "这是一段描述"
local luaBridge = require("cocos/cocos2d/luaj")
local fileNameArry = string.split(imgFullPath,"/")
local args = {imgFullPath, desc, fileNameArry[#fileNameArry]} --参数
local sig = "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V" --参数类型和返回值类型
local ok, result = luaBridge.callStaticMethod("org/cocos2dx/lua/AppActivity", "shareImgToCircleBySys", args, sig)
ios下的实现
1、AppController.mm中添加方法
#pragma System Share
+(void)shareBySys:(NSDictionary *)dict
{
NSLog(@"调用系统分享");
NSString *thumbImage = [[NSBundle mainBundle] pathForResource:@"res/icon" ofType:@"png"];
NSString *title = [dict objectForKey:@"title"];
NSString *url = [dict objectForKey:@"url"];
NSString *description = [dict objectForKey:@"description"];
NSString *imagepath = [dict objectForKey:@"imagepath"];
NSString *platform = [dict objectForKey:@"shareplatform"];
int sharetype = [[dict objectForKey:@"sharetype"] intValue];
int callback = [[dict objectForKey:@"callback"] intValue];
//创建
NSMutableArray* itemArr = [[NSMutableArray alloc] init];
//约定:sharetype==0表示分享到微信
if (sharetype == 0 && imagepath) {
//图片
NSData * data = [NSData dataWithContentsOfFile:imagepath];
UIImage *img = [UIImage imageWithData:data];
[itemArr addObject:img];
} else if (sharetype == 0 && url) {
//链接
NSData * data = [NSData dataWithContentsOfFile:thumbImage];
UIImage *img = [UIImage imageWithData:data];
[itemArr addObject:title];
[itemArr addObject:[NSURL URLWithString:url]];
[itemArr addObject:img];
[itemArr addObject:description];
} else if (sharetype == 0) {
//纯文字
}
//开启调用
UIActivityViewController* activity = [[UIActivityViewController alloc] initWithActivityItems:itemArr applicationActivities:nil];
//适配IPAD
if([activity respondsToSelector:@selector(popoverPresentationController)]){
activity.popoverPresentationController.sourceView = controller.view;
}
activity.completionWithItemsHandler = ^(UIActivityType _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
NSLog(@"activityType :%@", activityType);
if([activityType isEqualToString:@"com.tencent.xin.sharetimeline"]){
NSLog(@"微信回调");
}
if (completed) {
NSLog(@"completed");
}
else {
NSLog(@"cancel");
}
if(callback) {
cocos2d::LuaBridge::pushLuaFunctionById(callback);
cocos2d::LuaStack *stack = cocos2d::LuaBridge::getStack();
stack->pushString([platform UTF8String]);
stack->pushString([activityType UTF8String]);
stack->pushInt(completed);
stack->pushInt((int)activityError.code);
stack->executeFunction(4);
}
};
if (@available(iOS 11_0, *)) {
activity.excludedActivityTypes = @[UIActivityTypePostToFacebook,UIActivityTypePostToTwitter, UIActivityTypePostToWeibo,UIActivityTypeMessage,UIActivityTypeMail,UIActivityTypePrint,UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll,UIActivityTypeAddToReadingList,UIActivityTypePostToFlickr,UIActivityTypePostToVimeo,UIActivityTypePostToTencentWeibo,UIActivityTypeAirDrop,UIActivityTypeOpenInIBooks,UIActivityTypeMarkupAsPDF,@""];
} else {
activity.excludedActivityTypes = @[UIActivityTypePostToFacebook,UIActivityTypePostToTwitter, UIActivityTypePostToWeibo,UIActivityTypeMessage,UIActivityTypeMail,UIActivityTypePrint,UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll,UIActivityTypeAddToReadingList,UIActivityTypePostToFlickr,UIActivityTypePostToVimeo,UIActivityTypePostToTencentWeibo,UIActivityTypeAirDrop,UIActivityTypeOpenInIBooks];
}
//此controller为当前RootViewController
[controller presentViewController:activity animated:YES completion:nil];
}
2、AppController.mm中添加
static UIViewController *controller = nil;
让controller指向viewController
// Use RootViewController manage CCEAGLView
viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];
viewController.wantsFullScreenLayout = YES;
viewController.view = eaglView;
controller = viewController;
3、shareUtil中添加
function gt.shareBySys(imgPath,title,desc,url,customCallback)
--回调
local function definCallBack(platform, sharetype, state, errorcode)
--加入自己的回调
require("app/views/NoticeTips"):create("", string.format("%s|%s|%d|%d",platform,sharetype,state,errorcode), nil, nil, true)
end
callBridgeStaticMethod("shareBySys", {shareplatform="ios",description=desc, title=title,imagepath = imgPath,url=url,callback = definCallBack})
end
lua 层调用
local luaBridge = require("cocos/cocos2d/luaoc")
-- 如果 iconPath = nil 默认 res/icon.png 如果 iconPath 不为空 ,请传递 类似 res/test/icon.png description 字符串
luaBridge.callStaticMethod("AppController","registerSysShareCallFun",{scriptHandler = function() end});
luaBridge.callStaticMethod("AppController", "shareBySys",{localImage = gt.getSysShareImg() , shareplatform = "wx" })
网友评论