自定义头像选区

http://my.oschina.net/u/1582495/blog/390417?fromerr=bCEvIDTz

 

 

1、在ios/AppController.h 添加这两个协议 UIImagePickerControllerDelegate,UINavigationControllerDelegate

2、编写下面代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//显示照相机
+(void) showImagePicker:(NSDictionary *)info {
    callBackId = [[info objectForKey:@"listener"] intValue];
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.allowsEditing = true;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:imagePicker animated:YES completion:nil];
}
 
//选取照片完成
+(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSLog(@"%@",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 *imgFilePath = [documentsDirectory stringByAppendingPathComponent:@"headPhoto.png"];
    success = [fileManager fileExistsAtPath:imgFilePath];
    std::string newImgPath = cocos2d::CCFileUtils::getInstance()->getWritablePath() + "/headPhoto.png";
    if (success) {
        success = [fileManager removeItemAtPath:[NSString stringWithFormat:@"%s",newImgPath.c_str()] error:&error];
        NSLog(@"success 2 %d",success);
    }
    // 更改尺寸
    UIImage * smallImage = [self thumbnailWithImageWithoutScale:img size:CGSizeMake(80, 80)];
    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:[NSString stringWithFormat:@"%s",newImgPath.c_str()] atomically:YES];
    // 新的照片地址回调给lua
    cocos2d::LuaObjcBridge::pushLuaFunctionById(callBackId);
//    cocos2d::LuaObjcBridge::getStack()->pushString([imgFilePath cStringUsingEncoding:NSUTF8StringEncoding]);
    cocos2d::LuaObjcBridge::getStack()->pushString(newImgPath.c_str());
    cocos2d::LuaObjcBridge::getStack()->executeFunction(1);
    cocos2d::LuaObjcBridge::releaseLuaFunctionById(callBackId);
     
}
// 实现缩略图
+(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;
}

3、在lua里面实现

if device.platform == "ios" then
	local function callBack( imgFileName )
	        //重新加载文理
		cc.Director:getInstance():getTextureCache():reloadTexture(imgFileName)
		display.newSprite(imgFileName):addTo(self):pos(display.cx,display.cy)
	end
	luaoc.callStaticMethod("AppController","showImagePicker",{listener = callBack})
end

















/****************************************************************************

 Copyright (c) 2010-2013 cocos2d-x.org

 Copyright (c) 2013-2014 Chukong Technologies Inc.

 

 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.

 ****************************************************************************/

 

@class RootViewController;

 

@interface AppController : NSObject <UIAccelerometerDelegate, UIAlertViewDelegate, UITextFieldDelegate,UIApplicationDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

{

    UIWindow *window;

    RootViewController    *viewController;

    

}

@end

 










/****************************************************************************

 Copyright (c) 2010-2013 cocos2d-x.org

 Copyright (c) 2013-2014 Chukong Technologies Inc.

 

 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.

 ****************************************************************************/

 

#import <UIKit/UIKit.h>

#import "cocos2d.h"

 

#import "AppController.h"

#import "AppDelegate.h"

#import "RootViewController.h"

#import "platform/ios/CCEAGLView-ios.h"

#include "platform/ios/CCLuaObjcBridge.h"

@implementation AppController

 

#pragma mark -

#pragma mark Application lifecycle

 

// cocos2d application instance

static AppDelegate s_sharedApplication;

int callBackId;

//显示照相机

+(void) showImagePicker:(NSDictionary *)info {

    callBackId = [[info objectForKey:@"listener"] intValue];

    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];

    imagePicker.delegate = self;

    imagePicker.allowsEditing = true;

    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:imagePicker animated:YES completion:nil];

}

 

//选取照片完成

+(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{

    NSLog(@"%@",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 *imgFilePath = [documentsDirectory stringByAppendingPathComponent:@"headPhoto.png"];

    success = [fileManager fileExistsAtPath:imgFilePath];

    std::string newImgPath = cocos2d::FileUtils::getInstance()->getWritablePath() + "/headPhoto.png";

    if (success) {

        success = [fileManager removeItemAtPath:[NSString stringWithFormat:@"%s",newImgPath.c_str()] error:&error];

        NSLog(@"success 2 %d",success);

    }

    // 更改尺寸

    UIImage * smallImage = [self thumbnailWithImageWithoutScale:img size:CGSizeMake(105, 105)];

    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:[NSString stringWithFormat:@"%s",newImgPath.c_str()] atomically:YES];

    // 新的照片地址回调给lua

    cocos2d::LuaObjcBridge::pushLuaFunctionById(callBackId);

    //    cocos2d::LuaObjcBridge::getStack()->pushString([imgFilePath cStringUsingEncoding:NSUTF8StringEncoding]);

    cocos2d::LuaObjcBridge::getStack()->pushString(newImgPath.c_str());

    cocos2d::LuaObjcBridge::getStack()->executeFunction(1);

    cocos2d::LuaObjcBridge::releaseLuaFunctionById(callBackId);

    

}

// 实现缩略图

+(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;

}

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

 

    cocos2d::Application *app = cocos2d::Application::getInstance();

    app->initGLContextAttrs();

    cocos2d::GLViewImpl::convertAttrs();

 

    // Override point for customization after application launch.

 

    // Add the view controller's view to the window and display.

    window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];

    CCEAGLView *eaglView = [CCEAGLView viewWithFrame: [window bounds]

                                     pixelFormat: (NSString*)cocos2d::GLViewImpl::_pixelFormat

                                     depthFormat: cocos2d::GLViewImpl::_depthFormat

                              preserveBackbuffer: NO

                                      sharegroup: nil

                                   multiSampling: NO

                                 numberOfSamples: 0 ];

 

    [eaglView setMultipleTouchEnabled:YES];

    

    // Use RootViewController manage CCEAGLView

    viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil];

    viewController.wantsFullScreenLayout = YES;

    viewController.view = eaglView;

 

    // Set RootViewController to window

    if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0)

    {

        // warning: addSubView doesn't work on iOS6

        [window addSubview: viewController.view];

    }

    else

    {

        // use this method on ios6

        [window setRootViewController:viewController];

    }

    

    [window makeKeyAndVisible];

 

    [[UIApplication sharedApplication] setStatusBarHidden: YES];

 

    // IMPORTANT: Setting the GLView should be done after creating the RootViewController

    cocos2d::GLView *glview = cocos2d::GLViewImpl::createWithEAGLView(eaglView);

    cocos2d::Director::getInstance()->setOpenGLView(glview);

 

    app->run();

    return YES;

}

 

 

- (void)applicationWillResignActive:(UIApplication *)application {

    /*

     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

     */

    cocos2d::Director::getInstance()->pause();

}

 

- (void)applicationDidBecomeActive:(UIApplication *)application {

    /*

     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

     */

    cocos2d::Director::getInstance()->resume();

}

 

- (void)applicationDidEnterBackground:(UIApplication *)application {

    /*

     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.

     */

    cocos2d::Application::getInstance()->applicationDidEnterBackground();

}

 

- (void)applicationWillEnterForeground:(UIApplication *)application {

    /*

     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.

     */

    cocos2d::Application::getInstance()->applicationWillEnterForeground();

}

 

- (void)applicationWillTerminate:(UIApplication *)application {

    /*

     Called when the application is about to terminate.

     See also applicationDidEnterBackground:.

     */

}

 

 

#pragma mark -

#pragma mark Memory management

 

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {

    /*

     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.

     */

     cocos2d::Director::getInstance()->purgeCachedData();

}

 

 

- (void)dealloc {

    [super dealloc];

}

 

-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window

{

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {

        return UIInterfaceOrientationMaskAll;

    }

    else {

        return UIInterfaceOrientationMaskAllButUpsideDown;

    }

}

 

@end

 















posted @ 2015-12-08 20:53  一个橙子~  阅读(299)  评论(0编辑  收藏  举报