0

我有以下主要从 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 很陌生,因此感谢您的帮助

4

2 回答 2

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);

您的 crop 方法现在返回新裁剪的图像并将其存储在TopImage.


其他建议:

类名以大写字母开头,变量以小写字母开头。TopImage应该是真的topImage

另外,我总是在你的方法中使用命名参数,所以

-(void)cropImage:(UIImage *)image:(int)startCroppingPosition

应该是这样的

-(void)cropImage:(UIImage *)image startPosition:(int)startCroppingPosition

当您在一个月后重新使用它时,这将使您的代码更具可读性(我在过去很难学到这一点!)

于 2012-06-15T18:51:39.977 回答
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]; 

这应该可以按预期工作!

于 2012-06-15T18:51:18.977 回答