如何实时更改矩形的位置和大小?

时间:2011-06-19 14:19:34

标签: iphone objective-c xcode real-time

我想画一个矩形,可以实时改变矩形的位置和大小。

我尝试过两种方法,但视图不显示矩形。

你有什么建议或例子吗?

感谢您的帮助。

使用视图框(仅在重新启动应用时显示新矩形)

UIView * drawView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 10, 10)];
[self.view addSubview:drawView];
drawView.layer.borderColor = [[UIColor orangeColor] CGColor];
drawView.layer.borderWidth = 2;

drawView.frame = CGRectMake(r.x, r.y, r.width, r.height);

在drawRect中绘制

fav = [[FaceAugmentingView alloc] initWithFrame:[imageView frame]];
fav.backgroundColor = [UIColor clearColor];
[self.view addSubview: fav  ];
fav.face = CGRectMake(r.x, r.y, r.width, r.height);
[fav setNeedsDisplay];

1 个答案:

答案 0 :(得分:1)

我建议您添加一个方法,以便在需要更改时重新加载面。声明和数组将帮助我们跟踪我们添加的所有视图。

@interface FacesViewController: UIViewController
[..]
@property (nonatomic, retain) NSMutableArray * faceViews;

- (void)reloadFaces;
[..]
@end

然后实现reloadFaces这样的事情 -

- (void)reloadFaces {
    /* remove all current views we've added */
    for ( UIView * aView in self.faceViews ) {
        [aView removeFromSuperview];
    }
    [self.faceViews removeAllObjects];

    /* Add news ones */
    int numberOfFaces = [self numberOfFacesInImage];
    for ( int i = 0; i < numberOfFaces; i++ ) {
        CGRect faceFrame = [self frameForFaceAtIndex:i];

        UIView * drawView = [[[UIView alloc] initWithFrame:faceFrame] autorelease];
        drawView.layer.borderColor = [[UIColor orangeColor] CGColor];
        drawView.layer.borderWidth = 2;
        drawView.frame = CGRectMake(r.x, r.y, r.width, r.height);

        [self.view addSubview:drawView];
        [faceViews addObject:drawView];
    }
}

我希望在某种变化时调用reloadFacesnumberOfFacesInImageframeForFaceAtIndex:是您必须根据获取数据的方式实施的方法。您也可以替换它们以适合您的数据模型。不要忘记初始化faceViews