Cocos2d-x game in Android platform using umeng social components screenshot sharing implementation

Source: Internet
Author: User

Implementation steps simple example 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 (); // 'player' is an autorelisted object HelloWorld * layer = HelloWorld: create (); // add layer as a child to scene-> addChild (layer ); // return the scene r Eturn scene;} // on "init" you need to initialize your instancebool HelloWorld: init () {// 1. super init first if (! CCLayer: init () {return false;} CCSize visibleSize = CCDirector: sharedDirector ()-> getVisibleSize (); CCPoint origin = CCDirector: shareddire () -> 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 autorelpolicobject CCMenuItemImage * pCloseItem = CCMenuItemImage: create ("example", "CloseSelected.png", this, menu_selector (HelloWorld: menuCloseCallback )); pCloseItem-> setPosition (ccp (origin. x + visibleSize. width-pCloseItem-> getContentSize (). width/2, origin. y + pCloseItem-> getContentSize (). height/2); // authorize a platform CCMenuItemFont * authTextButton = CCMenuItemFont: create ("open sharing panel", 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 ;}// save the game screenshot void HelloWorld :: saveScreenShot () {//************************************* **************************************// screenshot static int index = 0; CCSize size = CCDirector: shareddire()-> 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-0000d.jpg", index ++); // save as jpeg bool result = texture-> saveToFile (imgName, kCCImageFormatJPEG); if (result) {// imagePath + = "screenshot.png"; imagePath + = imgName; CCLog ("# save scrshot", "### COCOS2D-X succeeded "); // set the image address to the java layer setScrShotPathToJava (imagePath. c_str () ;}}// pass the screenshot path to the java layer void HelloWorld: setScrShotPathToJava (const char * path) through a static function) {//************************************* * *********************************** JniMethodInfo methodInfo; // After the screen is captured, set the address to bool isHave = JniHelper: getStaticMethodInfo (methodInfo, "com/umeng/game/UmengGameActivity", "setImagePath ", "(Ljava/lang/String;) V"); if (isHave) {jstring imgPath = methodInfo. env-> NewStringUTF (path); // open umeng sharing platform in UmengGameActivity and select panel methodInfo. env-> CallStaticVoidMethod (methodInfo. classID, methodInfo. methodID, imgPath); methodInfo. env-> DeleteLocalRef (imgPath); methodInfo. env-> DeleteLocalRef (methodInfo. classID) ;}// screenshot first, pass the path to the java layer, and open the sharing panel void HelloWorld: openShare (CCObject * pSender) {# if CC_TARGET_PLATFORM = CC_PLATFORM_ANDROID saveScreenShot (); # elif CC_TARGET_PLATFORM = Success // 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: shareddire()-> end (); # if (CC_TARGET_PLATFORM = CC_PLATFORM_IOS) exit (0); # endif}

UmengGameActivity implementation at the Android code Layer
/*************************************** * *********************************** Copyright (c) 2010-2011 cocos2d-x.orghttp: // www. cocos2d-x.orgPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publi Sh, distriwing, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions: the above copyright notice and this permission notice shall be encoded inall copies or substantial portions of the Software. the software is provided "as is", without warranty of any kind, express orimplied, INCLUDING BUT NOT LIMITED The warranties of merchantability, fitness for a particle purpose and noninfringement. in no event shall theauthors or copyright holders be liable for any claim, damages or otherliability, 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 inthe 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. logoff; import android. text. textUtils; import android. util. log; import com. umeng. socialize. controller. requestType; import com. umeng. socialize. controller. UMServiceFactory; import com. ume Ng. socialize. controller. UMSocialService; import com. umeng. socialize. media. UMImage; public class UmengGameActivity extends Cocos2dxActivity {/*** Handler, used to wrap umeng's openShare method and ensure that the openShare method is executed in the UI thread */private static Handler mHandler = null; /*** Save the current Activity instance, static variable */private static Cocos2dxActivity mActivity = null;/*** umeng Social SDK instance, controller */private static UMSocialService mController = UMS of the entire SDK ErviceFactory. 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 (logoff. getMainLooper ();}/** (non-Javadoc) ** @ see org. coco S2dx. lib. cocos2dxActivity # onCreateView () */public Cocos2dxGLSurfaceView onCreateView () {Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView (this); // hello shocould create stengle bufferglSurfaceView. setEGLConfigChooser (5, 6, 5, 0, 16, 8); return glSurfaceView;} // screenshot path private static String scrshotImgPath = ""; /*** open the sharing panel */public static void openShare () {mHandler. postDelayed (new Runnable () {@ Overridepublic void run () {if (! TextUtils. isEmpty (scrshotImgPath) {mController. setShareMedia (new UMImage (mActivity, new File (scrshotImgPath); Log. d ("", "### set screenshot image");} mController. setmediacontent ("cocos2d-x screenshot sharing, image address:" + scrshotImgPath); // open umeng sharing platform choose panel mController. openShare (mActivity, false) ;}}, DELAY) ;}/ *** after setting the image, open the sharing panel directly * @ param path */public static void setImagePath (String path) {scrshotImgPath = path; // open the sharing panel openShare ();}/*** load cocos2dcpp. so */static {System. loadLibrary ("cocos2dcpp ");}}

Note that scrshotImgPath is a static member variable. Therefore, you must clear the image once it is used to avoid using the previous image.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.