如何不用图片绘制图形精灵

17 篇文章 0 订阅

我们有时常常需要一些圆形或者方形的背景,来修饰其他精灵,而专门画张图片又有点麻烦,这时就需要自己用程序来绘制了。

最常见的两种:

方形精灵

-(CCSprite*) createSpriteRectangleWithSize:(CGSize)size
{
    CCSprite *sprite = [CCSprite node];
    GLubyte *buffer = malloc(sizeof(GLubyte)*4);
    for (int i=0;i<4;i++) {buffer[i]=255;}
    CCTexture2D *tex = [[CCTexture2D alloc] initWithData:buffer pixelFormat:kCCTexture2DPixelFormat_RGB5A1 pixelsWide:1 pixelsHigh:1 contentSize:size];
    [sprite setTexture:tex];
    [sprite setTextureRect:CGRectMake(0, 0, size.width, size.height)];
    free(buffer);
    return sprite;
}

圆形精灵

-(CCSprite*) createSpriteCircleWithRadius:(float)radius
{
    
    CGSize circleSize = CGSizeMake(radius*2*CC_CONTENT_SCALE_FACTOR(), radius*2*CC_CONTENT_SCALE_FACTOR());
    CGContextRef context = CGBitmapContextCreate(NULL, circleSize.width, circleSize.height, 8, 0,CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedLast);
    float lengths[] = {10,10};
    CGContextSetLineDash(context, 0, lengths, 2);
    CGContextSetRGBStrokeColor(context, 0.65, 0.65, 0.65, 1.0);
    CGContextSetLineWidth(context, 2);
    
    CGContextAddArc(context, circleSize.width/2, circleSize.height/2 , circleSize.width/2, 0,2*M_PI,1);
    CGContextDrawPath(context,kCGPathStroke);
    
    CGImageRef shadowedCGImage = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    
    UIImage * shadowedImage = [UIImage imageWithCGImage:shadowedCGImage];
    CGImageRelease(shadowedCGImage);
    
    [[CCTextureCache sharedTextureCache] addCGImage:[shadowedImage CGImage] forKey:@"circleKey"];
    return [CCSprite spriteWithTexture:[[CCTextureCache sharedTextureCache] textureForKey:@"circleKey"]];
}


以上两种,分别用不同的方法来进行绘制,同理,修改内容,也可以绘制各种自己想要的图形,设置自己想要的颜色和透明度



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值