像素触摸的大致思路都是一样的,无论是-x中的版本还是html5中。
第一步:获得纹理的像素信息。
第二步:根据图片的像素信息获得触摸(点击)点上的像素信息。
第三步:触摸判断,是否透明。透明则不处理,不透明则触摸到了。
具体的实现思路:
目前我们基本上都是使用UIButton这个类,所以我只实现了这个的简单封装,其他的都类似。
第一步:修改Button的onTouchBegan函数,截取开始的触摸事件,在这个地方实现是否为透明区域的判断处理。
使用方法:
在创建按钮的地方,设置按钮是否使用像素触摸即可。
具体实现:
- cc.Sprite.prototype._pixels = [];
- cc.Sprite.prototype.readPixels = function(x,y){
- var w = this.width;
- var h = this.height;
- if(!this._pixels || this._pixels.length == 0){
- var canvas = cc.newElement("canvas"); // 创建一个新的元素节点
- canvas.width = w;
- canvas.height = h;
- var ctx = canvas.getContext("2d"); // 获得一个2d的画布(通过它就可以这个画布上的像素信息,我们只在上面绘制一张图片)
- ctx.drawImage(this.getTexture().getHtmlElementObj(),0); // 因此获得的像素信息也就等于是这个图片的像素信息</span>
- this._pixels = ctx.getImageData(0,w,h).data; // 获得像素信息
- }
- var idx = (h-y) * w * 4 + x * 4; // 根据触摸坐标得到像素上的索引
- return [this._pixels[idx],this._pixels[idx + 1],this._pixels[idx + 2],this._pixels[idx + 3]]; // 返回这个点上的的像素信息
- };
- ccui.Button.prototype.setPixelTouchEnabled = function (b) {
- this._pixelEnabled = b;
- };
- ccui.Button.prototype.getPixelTouchEnabled = function (b) {
- return this._pixelEnabled;
- };
- ccui.Widget.prototype.onTouchBegan = function (touch,event) {
- this._hit = false;
- if (this.isVisible() && this.isEnabled() && this._isAncestorsEnabled() && this._isAncestorsVisible(this) ){
- var touchPoint = touch.getLocation();
- this._touchBeganPosition.x = touchPoint.x;
- this._touchBeganPosition.y = touchPoint.y;
- if(this.hitTest(this._touchBeganPosition) && this.isClippingParentContainsPoint(this._touchBeganPosition))
- this._hit = true;
- var target = event.getCurrentTarget();
- if(target instanceof ccui.Button && target.getPixelTouchEnabled()){
- var locationInNode = target.convertToNodeSpace(touchPoint);
- //var locationInNode = touchPoint;
- var s = target.getContentSize();
- var rect = cc.rect(0,s.width,s.height);
- if (cc.rectContainsPoint(rect,locationInNode)) {
- var sp = target.getVirtualRenderer();
- var x = locationInNode.x;
- var y = locationInNode.y;
- if(sp instanceof cc.Sprite){
- var pexels = sp.readPixels(Math.round(x),Math.round(y));
- cc.log("alhpa : %d",(pexels[3]));
- if(pexels[3] > 0){
- // 非透明
- this._hit = true;
- }else{
- // 透明
- this._hit = false;
- }
- }
- }
- }
- }
- if (!this._hit) {
- return false;
- }
- this.setHighlighted(true);
- /*
- * Propagate touch events to its parents
- */
- if (this._propagateTouchEvents)
- {
- this.propagateTouchEvent(ccui.Widget.TOUCH_BEGAN,this,touch);
- }
- this._pushDownEvent();
- return true;
- };
最后补充:
当我写完canvas版本的时候,想到要做到位,肯定也要支持webGL。webGL的绘制方法和canvas不一样。但是找了半天,没有找到方法。于是我想,webGL严格来说是属于canvas上的内容。然后直接实验这段代码能不能在webGL模式下跑,测试后通过,没问题。
最近还在学习webGL,有结果了再补充原因。