我有以下代码,我大部分来自SO,但我的图像仍然没有被裁剪,我做错了什么?
@synthesize TopImage;
@synthesize BottomImage;
@synthesize RotaterImage;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
TopImage = [UIImage imageNamed:@"zero.png"];
[TopImage drawAtPoint:CGPointMake(0, 0)];
[self cropImage:TopImage:0];
[self addSubview:[[UIImageView alloc] initWithImage:TopImage]];
// BottomImage = [UIImage imageNamed:@"zero.png"];
// [BottomImage drawAtPoint:CGPointMake(0, 55)];
// [self cropImage:BottomImage:50];
// [self addSubview:[[[UIImageView alloc] initWithImage:BottomImage]retain]];
// RotaterImage = [UIImage imageNamed:@"zero.png"];
// [RotaterImage drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeNormal alpha:0];
// [self addSubview:[[[UIImageView alloc] initWithImage:RotaterImage]retain]];
// [self cropImage:RotaterImage:50];
}
return self;
}
-(void)cropImage:(UIImage *)image:(int)startCroppingPosition{
CGRect tempRect = CGRectMake(0, startCroppingPosition, 23, 40);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], tempRect);
// or use the UIImage wherever you like
image = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
}
我对IOS很新,所以感谢任何帮助
答案 0 :(得分:2)
您正在创建新的裁剪图片,但没有告诉init
方法:)
尝试此更改:
-(UIImage *)cropImage:(UIImage *)image:(int)startCroppingPosition{
CGRect tempRect = CGRectMake(0, startCroppingPosition, 23, 40);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], tempRect);
// or use the UIImage wherever you like
UIImage *newImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return newImage;
}
,在init
中,替换
[TopImage drawAtPoint:CGPointMake(0, 0)];
与
UIImageView* topImageView = [[UIImageView alloc] initWithImage:topImage];
topImageView.frame = CGRectMake(x,y,width,height);
您的裁剪方法现在返回新裁剪的图像,并将其存储在TopImage
。
其他建议:
类名以CapitalLetter开头,变量以小写开头。 TopImage
应该是topImage
。
另外,我总是在你的方法中使用命名参数,所以
-(void)cropImage:(UIImage *)image:(int)startCroppingPosition
应该是
-(void)cropImage:(UIImage *)image startPosition:(int)startCroppingPosition
当你在一个月的时间内回到它时,这将使你的代码更具可读性(我已经了解了过去的艰难方法!)
答案 1 :(得分:0)
您只是更改图像而不是UIImageView的图像,
我要做的是替换:
[self addSubview:[[UIImageView alloc] initWithImage:TopImage]];
带
UIImageView *iv = [[UIImageView alloc] initWithImage:TopImage]];
iv.tag = 1000 //number does not matter
[self.view addSubview:iv];
[iv release];
然后在裁剪图片中添加:
UIImageView *iv = [self.vief viewWithTag:1000];
iv.image = [UIImage imageWithCGImage:imageRef];
这应该按预期工作!