`
阿尔萨斯
  • 浏览: 4168306 次
社区版块
存档分类
最新评论

Cocos2d-x游戏在Android平台使用友盟社会化组件进行截图分享的实现

 
阅读更多

实现步骤简述

  1. 在Cocos2d-x游戏场景中添加一个按钮;
  2. 在该按钮的点击回调中截取游戏屏幕图像,并且保存到本地路径中;
  3. 将截屏图像的本地路径通过jni传递给java层;
  4. java层构建分享图片UMImage,并且设置给SDK Controller;
  5. 最后打开分享面板,选择平台分享即可。

简单示例

HelloWorld.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

class HelloWorld : public cocos2d::CCLayer
{
public:
    // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
    virtual bool init();  

    // there's no 'id' in cpp, so we recommend returning the class instance pointer
    static cocos2d::CCScene* scene();
    
    // a selector callback
    void menuCloseCallback(CCObject* pSender);
    
    void openShare(CCObject* pSender);

    void saveScreenShot();

    void setScrShotPathToJava(const char* path);

    // implement the "static node()" method manually
    CREATE_FUNC(HelloWorld);

};

#endif // __HELLOWORLD_SCENE_H__

HelloWorld.cpp
#include "HelloWorldScene.h"
#include "platform/android/jni/JniHelper.h"
#include <android/log.h>
#include <jni.h>

USING_NS_CC;
using namespace std;

CCScene* HelloWorld::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    HelloWorld *layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
    
    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
                                        "CloseNormal.png",
                                        "CloseSelected.png",
                                        this,
                                        menu_selector(HelloWorld::menuCloseCallback));
    
	pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
                                origin.y + pCloseItem->getContentSize().height/2));

        // 授权某平台
    CCMenuItemFont *authTextButton = CCMenuItemFont::create("打开分享面板",this , menu_selector(HelloWorld::openShare));
    authTextButton->setPosition(ccp(150,320));

    // create menu, it's an autorelease object
    CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
    pMenu->setPosition(CCPointZero);
    pMenu->addChild(authTextButton, 1);
    this->addChild(pMenu, 1);

    /////////////////////////////
    // 3. add your codes below...

    // add a label shows "Hello World"
    // create and initialize a label
    
    CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Arial", 24);
    
    // position the label on the center of the screen
    pLabel->setPosition(ccp(origin.x + visibleSize.width/2,
                            origin.y + visibleSize.height - pLabel->getContentSize().height));

    // add the label as a child to this layer
    this->addChild(pLabel, 1);

    // add "HelloWorld" splash screen"
    CCSprite* pSprite = CCSprite::create("HelloWorld.png");

    // position the sprite on the center of the screen
    pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));

    // add the sprite as a child to this layer
    this->addChild(pSprite, 0);
    
    return true;
}

// 保存游戏截屏
void HelloWorld::saveScreenShot()
{
      // ***************************************************************************
    // 截屏
    static int index = 0 ;
    CCSize size = CCDirector::sharedDirector()->getWinSize();

    CCLog("Window Size, width = %d, height = %d.", (int)size.width, (int)size.height );
    CCRenderTexture* texture = CCRenderTexture::create((int)size.width, (int)size.height, kCCTexture2DPixelFormat_RGBA8888);    
    texture->setPosition(ccp(size.width/2, size.height/2));    
    texture->begin();
    CCDirector::sharedDirector()->getRunningScene()->visit();
    texture->end();

    string imagePath = CCFileUtils::sharedFileUtils()->getWritablePath() ;
    if ( imagePath.length() == 0 )
    {
      return ;
    }

    // imagePath = imagePath.c_str() ;

    char imgName[20] ;
    sprintf(imgName, "screenshot-%d.jpg", index++);

     //保存为jpeg  
    bool result = texture->saveToFile(imgName, kCCImageFormatJPEG); 
    if ( result ) 
    {
        // imagePath += "screenshot.png";
        imagePath += imgName ;
        CCLog("#save scrshot", "#### COCOS2D-X截图成功");
        // 将图片地址设置给java层
        setScrShotPathToJava(imagePath.c_str());
    } 
}

// 将截屏图片的路径通过静态函数传递给java层
void HelloWorld::setScrShotPathToJava(const char* path)
{
        // ***************************************************************************
        JniMethodInfo methodInfo;
        //  获截完屏幕以后将地址设置到java层中
        bool isHave = JniHelper::getStaticMethodInfo(methodInfo,
                                  "com/umeng/game/UmengGameActivity", "setImagePath", "(Ljava/lang/String;)V");
          
        if ( isHave )  
        {
            jstring imgPath = methodInfo.env->NewStringUTF(path) ;
             // 实际调用UmengGameActivity中打开umeng分享平台选择面板  
             methodInfo.env->CallStaticVoidMethod( methodInfo.classID, methodInfo.methodID, imgPath);
             methodInfo.env->DeleteLocalRef(imgPath);
             methodInfo.env->DeleteLocalRef(methodInfo.classID);
        }  
}

// 先截屏,然后将路径传递给java层,最后打开分享面板
void HelloWorld::openShare(CCObject* pSender) {

#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
        saveScreenShot();
    
#elif CC_TARGET_PLATFORM == CC_PLATFORM_IOS
    
    // TODO 
    
#endif

}


void HelloWorld::menuCloseCallback(CCObject* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
    CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
    CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
#endif
}

Android代码层的UmengGameActivity实现
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 ****************************************************************************/
package com.umeng.game;

import java.io.File;

import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.UMImage;

public class UmengGameActivity extends Cocos2dxActivity {

	/**
	 * Handler, 用于包装友盟的openShare方法,保证openShare方法在UI线程执行
	 */
	private static Handler mHandler = null;
	/**
	 * 保存当前Activity实例, 静态变量
	 */
	private static Cocos2dxActivity mActivity = null;
	/**
	 * 友盟Social SDK实例,整个SDK的Controller
	 */
	private static UMSocialService mController = UMServiceFactory
			.getUMSocialService("com.umeng.cocos2dx", RequestType.SOCIAL);
	/**
	 * 
	 */
	private static final int DELAY = 100;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.cocos2dx.lib.Cocos2dxActivity#onCreate(android.os.Bundle)
	 */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActivity = this;
		mHandler = new Handler(Looper.getMainLooper());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.cocos2dx.lib.Cocos2dxActivity#onCreateView()
	 */
	public Cocos2dxGLSurfaceView onCreateView() {
		Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
		// hello should create stencil buffer
		glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);

		return glSurfaceView;
	}

        // 截屏路径
	private static String scrshotImgPath = "";

	/**
	 * 打开分享面板
	 */
	public static void openShare() {

		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {

				if (!TextUtils.isEmpty(scrshotImgPath)) {
					mController.setShareMedia(new UMImage(mActivity, new File(
							scrshotImgPath)));
					Log.d("", "### 设置截屏图片");
				}
				mController.setShareContent("cocos2d-x截屏分享, 图片地址 : "
						+ scrshotImgPath);
				// 打开友盟的分享平台选择面板
				mController.openShare(mActivity, false);
			}
		}, DELAY);
	}

	/**
	 * 设置图片以后,直接打开分享面板
	 * @param path
	 */
	public static void setImagePath(String path) {
		scrshotImgPath = path;
		// 打开分享面板
		openShare();
	}

	/**
	 * 加载cocos2dcpp.so
	 */
	static {
		System.loadLibrary("cocos2dcpp");
	}
}

注意,scrshotImgPath是静态成员变量,因此使用完图片一次后需要清空,避免使用上次的截图图像。

效果图



分享到:
评论

相关推荐

    Cocos2d-x实战:JS卷——Cocos2d-JS开发

    Cocos2d-x实战:JS卷——Cocos2d-JS开发内容简介:本书是介绍Cocos2d-x游戏编程和开发技术书籍,介绍了使用Cocos2d-JS中核心类、瓦片地图、物理引擎、音乐音效、数据持久化、网络通信、性能优化、多平台发布、程序...

    Cocos2D-X游戏开发技术精解

     《Cocos2D-X游戏开发技术精解》详细介绍如何使用Cocos2D-X引擎开发自己的移动平台游戏。全书共15章,主要内容包括:Cocos2D-X引擎简介;如 资源太大,传百度网盘了,链接在附件中,有需要的同学自取。

    精通COCOS2D-X游戏开发 基础卷_2016.4-P399-13961841.pdf

    精通COCOS2D-X游戏开发 精通COCOS2D-X游戏开发 精通COCOS2D-X游戏开发 精通COCOS2D-X游戏开发 精通COCOS2D-X游戏开发

    Cocos2D-X游戏开发技术精解.pdf

    《Cocos2D-X游戏开发技术精解》详细介绍如何使用Cocos2D-X引擎开发自己的移动平台游戏。全书共15章,主要内容包括:Cocos2D-X引擎简介;如何建立跨平台的开发环境;引擎的核心模块——渲染框架;如何实现动态画面和...

    大富翁手机游戏开发实战基于Cocos2d-x3.2引擎

    资源名称:大富翁手机游戏开发实战基于Cocos2d-x3.2引擎内容简介:李德国编著的《大富翁手机游戏开发实战(基于 Cocos2d-x3.2引擎)》使用Cocos2d-x游戏引擎技术,带领读者一步一步从零开始进行大富翁移动游戏的开发...

    Cocos2d-x游戏编程——C++篇 .iso

    Cocos2d-x游戏编程——C++篇(电子工业出版社,徐飞 著)书本配套的光盘代码,

    精通Cocos2d-x游戏开发(进阶卷)源代码

    精通Cocos2d-x游戏开发(进阶卷)源代码 精通Cocos2d-x游戏开发(进阶卷)源代码 精通Cocos2d-x游戏开发(进阶卷)源代码

    cocos2d-x-2.1.5

    cocos2d-x-2.1.5

    cocos2d-x事件类

    在使用cocos2d-x开发游戏的过程中,为了实现逻辑和显示相分离。 在下通宵了一个晚上,写出了该事件类。 谨记,该事件只能用于cocos2d-x中。 事件发送者需要继承EventDispatcher类 事件接收者需要继承EventHandle类...

    cocos2d-x游戏开发实战精解

    本光盘是《Cocos2d-x游戏开发实战精解》一书的配书光盘,内容介绍如下。 (1)本书教学视频:该文件夹收录了本书的配套多媒体教学视频,可用暴风影音等视频播放器播放。 (2)本书源文件:该文件夹收录了本书涉及...

    Cocos2d-x高级开发教程

    Cocos2d-x是移动跨平台开发最流行的游戏引擎,而本书是一本很全面的、比较‘接地气’的游戏开发教程。书中汇聚了热门手机游戏《捕鱼达人》开发的实战经验,作者从最基础的内容开始,逐步深入地介绍了Cocos2d-x的相关...

    Cocos2d-x 3.x游戏开发实战pdf含目录

    Cocos2d-x 3.x游戏开发实战pdf含目录,内容详细,强烈推荐给大家。

    Cocos2d-x-3.x游戏开发之旅

    Cocos2d-x-3.x游戏开发之旅-钟迪龙著 全新pdf版和附书代码(代码为工程文件,可复制) 附带目录标签

    实例妙解Cocos2D-X游戏开发

    一线资深游戏开发工程师根据Cocos2D-X 最新版本撰写,Cocos2D-X创始人王哲、CSDN创始人蒋涛联袂推荐 完全通过真实游戏案例驱动,不仅将Cocos2D-X的各种功能、原理、技巧融入其中,而且还详细讲解了空战类、塔防类、...

    cocos2d-x游戏代码

    cocos2d-x游戏代码

    cocos2d-x实战项目

    cocos2d-x实战项目 01.cocos2d-x原理及环境配置.rar 03.cocostudio使用方法及UI控制.rar 04.XML文件读取与骨骼动画.rarcocos2d-x实战项目 01.cocos2d-x原理及环境配置.rar 03.cocostudio使用方法及UI控制.rar 04.XML...

    教你用Cocos2D-X开发跨平台移动应用

    Cocos2d-x源于Cocos2d,是一款开源游戏引擎项目,是一款基于对原有iOS平台cocos2d重写为C++的开源代码,封装了OpenGL,Box2d,LibCurl,LibPng等开源的跨平台代码。由于基于C++和STL特点使其广泛应用于游戏开发、移动...

    cocos2d-x-3.2旧版引擎下载

    cocos2d-x-3.2下载,不多说。或者可以下载另一个资源 cocos引擎老版本集合(cocos2d-x-2.2.1 - 3.5) http://download.csdn.net/download/crazymagicdc/9982656

    cocos2d-x游戏实例-纵版射击游戏(cocos2d-x 2.0.4)

    本人提交源码进行了版本移植并修改了一个bug,目前使用VS2008+cocos2d-x,2.0.4版本编译测试过(需要注意的是,我的IDE环境中是将COCOS2d-x的头文件和库文件设置到了VS环境中对所有项目生效,并没有单独对特定的COCOS...

    大富翁手机游戏开发实战 基于Cocos2d-x3.2引擎

    李德国编著的《大富翁手机游戏开发实战(基于 Cocos2d-x3.2引擎)》使用Cocos2d-x游戏引擎技术,带领读者一步一步从零开始进行大富翁移动游戏的开发。本书根据大富翁项目一一展开讲解游戏开发过程中涉及的各方面内容...

Global site tag (gtag.js) - Google Analytics