开发者社区> 问答> 正文

关于设置CCSprite的框架解答

需要使用CCSprite以多种尺寸显示图片。通常添加到CCSprite的图片都有固定的宽高。有没有方法能让我像下面代码一样,不用一开始手动设置图片的尺寸。然后将图片放到ccpsrite。

-(UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize image:(UIImage*)sourceImage
{
    UIImage *newImage = sourceImage;
CGSize imageSize = sourceImage.size;

/// Source image is of desired size or desired size 0x0, no change is done
if (!CGSizeEqualToSize(targetSize, CGSizeZero) && !CGSizeEqualToSize(imageSize, targetSize))
{
    CGFloat aspectRatio = imageSize.width / imageSize.height;
    CGFloat newAspectRatio = targetSize.width / targetSize.height;

    CGSize tempSize = targetSize;
    if (newAspectRatio < aspectRatio)
    {
        tempSize.width = targetSize.width * aspectRatio / newAspectRatio;
    }
    else
    {
        tempSize.height = targetSize.height * newAspectRatio / aspectRatio;
    }
    UIGraphicsBeginImageContext(targetSize);
    [sourceImage drawInRect:CGRectMake((targetSize.width - tempSize.width) / 2.0, (targetSize.height - tempSize.height) / 2.0, tempSize.width, tempSize.height)];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

}
return newImage;
}

展开
收起
爵霸 2016-03-19 11:28:25 1828 0
1 条回答
写回答
取消 提交回答
  • 可以调整CCSprite. CCSpriteCCNode的子类,CCNode有这些属性:

    /** The scale factor of the node. 1.0 is the default scale factor. It modifies the X and Y scale at the same time. */
    @property(nonatomic,readwrite,assign) float scale;
    /** The scale factor of the node. 1.0 is the default scale factor. It only modifies the X scale factor. */
    @property(nonatomic,readwrite,assign) float scaleX;
    /** The scale factor of the node. 1.0 is the default scale factor. It only modifies the Y scale factor. */
    @property(nonatomic,readwrite,assign) float scaleY;
    2019-07-17 19:07:50
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载