4

画面をタップしたところに縦線を引きたい。平均的な指の幅は 1 ピクセル幅よりも広いため、これを「段階的に」実行したいと考えています。基本的に25pxごとにしか線が引けません。そして、線を引くことができる最も近い場所を見つけたいと思います。

たとえば、指が上のビューの左側から 30 ピクセルをタップした場合、ビューの左側から 25 ピクセルの垂直線を描きたいとします。画面を左から 40 ピクセルタップした場合、左から 50 ピクセルのところに線を描画します。(したがって、25ピクセルごとに1本の線しか存在できず、最も近いものを描きたい.

どうすればこれを行うことができますか?

線を引くのは簡単です:

UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(100.0, 0.0, 1, 320.0)];
lineView.backgroundColor = [UIColor whiteColor];
[parentView addSubview:lineView];

しかし、ユーザーが画面をタップした場所を見つける方法がわかりません。

4

4 に答える 4

1

25 ポイントの境界に位置合わせされた最も近い垂直線を選択するには、これを使用して正しい x 値を計算します。

CGFloat   spacing = 25.0f;
NSInteger lineNumber = (NSInteger)((touchPoint.x + (spacing / 2.0f)) / spacing);
CGFloat   snapX = spacing * lineNumber;

上記のコードで何が起こるかを次に示します。

  1. 間隔値の半分をタッチ ポイントに追加します。これは、次のステップの「スナップ」プロセスで常に前の行が検出されるためです。間隔値の半分を追加することで、最も近い行に確実に「スナップ」します。
  2. 間隔で割り、値を整数にキャストして、行番号を計算します。これにより、結果の小数部分が切り捨てられるため、整数の行番号 (0、1、2、3 など) が得られます。
  3. 元の間隔を掛けて、描画する線の実際の x 値 (0、25、50、75 など) を取得します。
于 2012-06-17T20:36:14.093 に答える
0

画面全体(ステータスバーを除く)をカバーする透過的なカスタムUIViewを作成し、そのをオーバーライドします(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
次の方法でタッチポイントを取得できます。

  UITouch *touch = [touches anyObject];
  CGPoint touchPoint = [touch locationInView:self]; 
于 2012-06-17T14:08:49.280 に答える
0

ssteinbergコードを使用できます。

  UITouch *touch = [touches anyObject];
  CGPoint touchPoint = [touch locationInView:self]; 

または、UITapGestureRecognizerをビューに追加します。これはおそらく簡単です。

UITapGestureRecognizer* tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[yourParentView addGestureRecognizer:tapRecognizer];
[tapRecognizer release];

..。

- (IBAction)handleTap:(UITapGestureRecognizer *)recognizer {
    CGPoint touchPoint = [recognizer locationInView:self.view];

..。

さらに、次のようなものを追加して、25pxごとに線を引きます。

  CGFloat padding = 25.0;
  NSInteger xPosition = round(touchPoint.x / padding) * padding;
  [self drawLineAt:xPosition];
于 2012-06-17T16:16:10.217 に答える
0

適切な場合は、これを参照してください。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

if (lineView) {
    [lineView removeFromSuperview];

    NSSet *allTouchesSet = [event allTouches]; 
    NSArray *allTouches = [NSArray arrayWithArray:[allTouchesSet allObjects]];   
    int count = [allTouches count];

    if (count  == 1) {

        UITouch *touch = [[event allTouches] anyObject];
        tapPoint = [touch locationInView:self];
        NSLog(@"tapPoint: %@",NSStringFromCGPoint(tapPoint));

        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(tapPoint.x, 0.0, 1, 320.0)];
        lineView.backgroundColor = [UIColor whiteColor];
        [parentView addSubview:lineView];


    }
}

}

于 2012-06-22T13:06:39.730 に答える