设置 CCSprite 的框架?
Posted
技术标签:
【中文标题】设置 CCSprite 的框架?【英文标题】:Set frame of CCSprite? 【发布时间】:2013-05-30 13:29:40 【问题描述】:我有一张图片,我想用 CCSprite 显示不同的尺寸。我通常知道 CCSprite 只添加图像宽度和高度的图像,但我想知道是否有任何方法,所以我不必先手动缩放图像,如下所示,然后将图像提供给 ccpsrite?? p>
-(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;
【问题讨论】:
【参考方案1】:您可以扩展您的CCSprite
。 CCSprite
是CCNode
的子类,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;
【讨论】:
【参考方案2】:您可以添加一个自定义类,比如 FlexSprite 并执行此操作
在 FlexSprite.h 中
@interface FlexSprite : CCSprite
+(FlexSprite*)spriteWithFile:(NSString *)imageName frame:(CGSize )size;
-(id)initWithFile:(NSString *)imageName frame:(CGSize )size;
@end
在 FlexSprite.m 中
#import "FlexSprite.h"
@implementation FlexSprite
-(id)initWithFile:(NSString *)imageName frame:(CGSize )size
self = [super initWithFile:imageName];
if (self)
self.scaleX = size.width/self.contentSize.width;
self.scaleY = size.height/self.contentSize.height;
return self;
+(FlexSprite *)spriteWithFile:(NSString *)imageName frame:(CGSize )size
return [[[self alloc]initWithFile:imageName frame:size]autorelease];
@end
【讨论】:
以上是关于设置 CCSprite 的框架?的主要内容,如果未能解决你的问题,请参考以下文章