现实中需要实现把已知大图剪裁成规定圆形图片,需要使用一个圆形背景和已知大图进行正片叠底,圆形背景除了中间的圆其他地方为黑色,这样融合后黑色吞掉圆形区域外的颜色,达到剪裁效果
黑色背景图如下:
步骤如下:
传入参数,背景,遮罩,尺寸,target等
ChapterInfoManager.getTextureByHeroBody = function (chapter_info,target) {
var key_path = ChapterInfoManager._local_image_key+ "_Card_" +chapter_info.icon_body + ".png";
var blend_iamge_path = chapter_info.icon_image_path;
var mask_image_path = "res/ui/common/Temporary-head-2.png";
var size_render = cc.size(313,314);
var blend_conf = chapter_info.blend_conf;
var texture_conf = HelpTool.createTextureAndSaveLocal(key_path,blend_iamge_path,mask_image_path,blend_conf,size_render);
if(target && texture_conf.texture){
target.loadTextureFromMemory(texture_conf.texture);
target.setScaleY(texture_conf.flip);
}
return texture_conf.texture;
}
根据texture从本地读取并存储
HelpTool.createTextureAndSaveLocal = function (keyPath,bImagePath,mImagePath,bConf,sRender,bf) {
var _texture = null;
var flip = 1.0;
if(_texture = HelpTool.getImageFromLocal(keyPath)){
flip = 1.0;
}else{
var renderTexture = HelpTool.blendImage(mImagePath,bImagePath,bConf,sRender,bf);
if(_texture =HelpTool.saveImageToLocal(renderTexture,keyPath)){
flip = -1.0;
}else{
_texture = HelpTool.blendImage(mImagePath,bImagePath,bConf,sRender,bf).getSprite().getTexture();
flip = -1.0;
}
}
return {texture:_texture,flip:flip};
};
HelpTool.getImageFromLocal = function(name){
var data_path = jsb.fileUtils.getWritablePath()+ name;
var bRet =null;
if(jsb.fileUtils.isFileExist(data_path)){
var temp_sprite = cc.Sprite.create(data_path);
if(temp_sprite){
return temp_sprite.getTexture();
}else{
return null;
}
}else{
bRet= null;
}
return bRet;
}
HelpTool.saveImageToLocal = function(renderTexture,keyPath){
if(renderTexture && keyPath){
renderTexture.saveToFile(keyPath);
var sprite = renderTexture.getSprite();
return sprite.getTexture();
}
return false;
}
最重要的一步,根据地图和遮罩,尺寸,缩放遮罩,根据坐标偏移混合配置进行texture混合并返回
HelpTool.blendImage = function (maskImg,bImg,bconf,renderSize,bf) {
var size_render = renderSize? renderSize : cc.size(313,314);
var blend_conf = bconf ? bconf : {x:0,y:0,s:1.0};
var mask_blend_conf = bf ? bf : { src: cc.ZERO, dst: cc.ONE_MINUS_SRC_ALPHA };
var mask_sprite = cc.Sprite.create(maskImg);
var blend_pos = cc.p(size_render.width * 0.5, size_render.height * 0.5);
mask_sprite.setPosition(blend_pos);
mask_sprite.setScale(size_render.width / mask_sprite.getContentSize().width);
mask_sprite.setBlendFunc(mask_blend_conf);
var head_sprite = cc.Sprite.create(bImg);
head_sprite.setPosition(cc.p(size_render.width * 0.5 + blend_conf.x, size_render.height * 0.2 + blend_conf.y));
head_sprite.setScale(blend_conf.s);
var renderTexture = cc.RenderTexture.create(size_render.width, size_render.height);
if (null != renderTexture) {
renderTexture.begin();
head_sprite.visit();
mask_sprite.visit();
renderTexture.end();
}
return renderTexture;
}