【问题标题】:How to change a rectangle's position and size realtime?如何实时更改矩形的位置和大小?
【发布时间】:2011-06-19 14:19:34
【问题描述】:

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

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

你有什么建议或例子吗?

感谢您的帮助。

使用视图框架(它只在重新启动应用时显示新的矩形)

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

【问题讨论】:

  • 如果您不告诉我们您使用的是哪种语言/开发环境,我们无能为力。
  • 它被标记为 iphone - 这意味着 大多数 情况下是 Xcode/Objective-C/Cocoa-Touch。

标签: iphone objective-c xcode real-time


【解决方案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

【讨论】:

  • 两种方法我都试过了,但是视图没有显示矩形
  • 实时你的意思是你希望它跟随触摸?
  • 不跟随触摸。当我检测到一张脸时,我想在脸周围画一个矩形。对于您的第一种方法,只有当我重新启动应用程序时,它才会显示视图,然后它不会改变。我需要再次重新启动应用程序以使其新框架可用。你有什么建议吗?感谢您的帮助
  • 好像可以用,我又试了一次,和用view frame一样。该视图仅在重新启动应用程序时才显示新矩形。我很困惑,为什么?我已经删除并重新添加了带有新框架的drawview。
  • 是的!但那是因为您只是在开始时添加了框架,而后来没有更改。
猜你喜欢
  • 2014-05-02
  • 2021-07-19
  • 2019-01-07
  • 1970-01-01
  • 2020-04-17
  • 2010-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多