3

単純なUIView拡張機能でdrawRectメソッドをオーバーライドして、角が丸い長方形を描画し、それを黒色で塗りつぶし、タッチでサイズを変更するようにビューをアニメーション化しようとしました。つまり、サイズを変更すると、コンテキストがずっと同じままであるかのように、図面が完全に変形します。drawRectは、アニメーション中に呼び出されることはありません。ただし、アニメーションの後にビューにそれ自体を描画するように指示すると、正しく描画されます。

図面が変形することなく、サイズ変更をアニメーション化するにはどうすればよいですか?

- (void)drawRect:(CGRect)rect {
  CGContextRef context = UIGraphicsGetCurrentContext();  
  CGFloat radius = rect.size.height * 0.5f;  

  CGMutablePathRef path = CGPathCreateMutable();

  CGPathMoveToPoint(path, NULL, CGRectGetMidX(rect), CGRectGetMinY(rect));
  CGPathAddArcToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMinY(rect), 
                  CGRectGetMaxX(rect), CGRectGetMaxY(rect), radius);
  CGPathAddArcToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMaxY(rect), 
                  CGRectGetMinX(rect), CGRectGetMaxY(rect), radius);
  CGPathAddArcToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMaxY(rect), 
                  CGRectGetMinX(rect), CGRectGetMinY(rect), radius);
  CGPathAddArcToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect), 
                  CGRectGetMaxX(rect), CGRectGetMinY(rect), radius);
  CGPathCloseSubpath(path);

  CGContextSaveGState(context);
  CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
  CGContextAddPath(context, path);
  CGContextFillPath(context);
  CGContextRestoreGState(context);
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  [UIView animateWithDuration:1.f animations:^{
    self.frame = CGRectInset(self.frame, 0.f, -100.f);
  }];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  [UIView animateWithDuration:1.f animations:^{
    self.frame = CGRectInset(self.frame, 0.f, +100.f);
  }];
}
4

1 に答える 1

2

UIView の角を丸くしたい場合は、drawRect を明示的に再定義する必要はありません。UIView のレイヤー プロパティを変更する簡単な方法があります。ビューとその境界線は、アニメーション中に正しく描画されます。

// Make your view background color black
myView.backgroundColor = [UIColor blackColor];

// The following will allow you to change the color/border width/ corner radius of your UIView
myView.layer.borderColor  = [UIColor whiteColor].CGColor;
myView.layer.borderWidth  = kDefaultBorderWidth;
myView.layer.cornerRadius = kDefaultBorderRadius;

を .m ファイルに含め、#import <QuartzCore/QuartzCore.h>インポートしたことを確認してください。QuartzCore.framework

于 2012-08-23T06:38:10.257 に答える