首页 > 代码库 > 什么是锚点(AnchorPoint)

什么是锚点(AnchorPoint)

1.锚点通常是图形的几何中心,

AnchorPoint(x,y)的两个参量x和y的取值通常都是0到1之间的实数,表示锚点相对于节点长宽的位置。

例如,把节点左下角作为锚点,值为(0,0);

把节点的中心作为锚点,值为(0.5,0.5);

把节点右下角作为锚点,值为(1,0)。

精灵的AnchorPoint默认值为(0.5,0.5),其他节点的默认值为(0,0),如CCLayer。

相关的操作:setAnchorpoint(0,0);

影响: 1.挂载位置,   2.缩放,     3.旋转

myAnchorPoint.h

#pragma once#include "cocos2d.h"USING_NS_CC;class MyAnchorPoint:public CCLayer{public:    static CCScene * scene();    static MyAnchorPoint *create();    bool init();    /*原始绘图*/    void draw();    /*屏幕尺寸的大小*/    CCSize winSize;};

myAnchorPoint.cpp

#include "MyAnchorPoint.h"/*创建一个场景*/CCScene * MyAnchorPoint::scene(){    CCScene * scene = CCScene::create();    MyAnchorPoint * layer = MyAnchorPoint::create();    scene->addChild(layer);    return scene;}/*创建一个图层*/MyAnchorPoint *MyAnchorPoint::create(){    MyAnchorPoint * pRet = new MyAnchorPoint();    if (pRet && pRet->init())    {        pRet->autorelease();    }    else    {        delete pRet;        pRet = NULL;    }    return pRet;}/*初始化图层*/bool MyAnchorPoint::init(){    /*先初始化父类*/    CCLayer::init();    /*获取屏幕尺寸的大小*/    winSize = CCDirector::sharedDirector()->getWinSize();    /*创建一个精灵,测试锚点对挂载位置的影响*/    //CCSprite *spr = CCSprite::create("anchor3.png");    /*创建一个精灵,测试锚点对缩放的影响*/    /*CCSprite *spr = CCSprite::create("anchor1.png");    spr->setScale(2.0f);*/        /*创建一个精灵,测试锚点对旋转的影响*/    CCSprite *spr = CCSprite::create("anchor2.png");    /*以锚点为支点旋转30度*/    spr->setRotation(30.0f);    /*设置精灵的位置*/    spr->setPosition(ccp(winSize.width/2, winSize.height/2));    /*设置锚点不同,挂载位置则不同,默认锚点是在几何中心*/    //spr->setAnchorPoint(ccp(0, 0));    //spr->setAnchorPoint(ccp(0, 1));    /*spr->setAnchorPoint(ccp(1, 0));    spr->setAnchorPoint(ccp(1, 1));*/    /*将精灵添加进图层*/    this->addChild(spr);    return true;}void MyAnchorPoint::draw(){    /*设置绘图的颜色,默认为白色*/    ccDrawColor4B(255, 0, 0, 255);    /*画线*/    ccDrawLine(ccp(0, winSize.height / 2), ccp(winSize.width,winSize.height/2));    ccDrawColor4B(255, 255, 0, 255);    ccDrawLine(ccp(winSize.width/2, 0), ccp(winSize.width/2, winSize.height));}

 

什么是锚点(AnchorPoint)