0

UIImageViewに線を引く方法は?UIImageViewサブクラスを使用していますが、drawRect:メソッドをサポートしていません。画像ビューに線を引きたい。これどうやってするの?私を助けてください。線を引くために以下のコードを使用しています。

- (void)drawRect:(CGRect)rect {
    CGContextRef c = UIGraphicsGetCurrentContext();

    CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
    CGContextSetStrokeColor(c, red);
    CGContextBeginPath(c);
    CGContextMoveToPoint(c, 5.0f, 5.0f);
    CGContextAddLineToPoint(c, 50.0f, 50.0f);
    CGContextStrokePath(c);
}
4

4 に答える 4

5

次のコードは、元の画像と同じサイズの新しい画像を作成し、元の画像のコピーを新しい画像に描画してから、新しい画像の上部に沿って1ピクセルの線を描画することで機能します。

// UIImage *originalImage = <the image you want to add a line to>
// UIColor *lineColor = <the color of the line>

UIGraphicsBeginImageContext(originalImage.size);

// Pass 1: Draw the original image as the background
[originalImage drawAtPoint:CGPointMake(0,0)];

// Pass 2: Draw the line on top of original image
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 1.0);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, originalImage.size.width, 0);
CGContextSetStrokeColorWithColor(context, [lineColor CGColor]);
CGContextStrokePath(context);

// Create new image
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

// Tidy up
UIGraphicsEndImageContext();
于 2013-07-10T07:28:44.463 に答える
1

まず、私はを使用しませんUIImageView。実際、ドキュメントには...

サブクラスにカスタム描画コードが必要な場合は、基本クラスとしてUIViewを使用することをお勧めします。

を使用しUIViewます。

サブビューをUIView追加し、そこに画像を配置します。これで、の方法でUIImageViewカスタム描画を行うことができ、画像の上に表示されます。drawRectUIView

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);

    CGContextSetLineWidth(context, 5.0);

    CGContextStrokeRect(context, self.bounds);
}

これが機能していない場合は、drawRectメソッドが呼び出されていない可能性があります。ブレークポイントを設定してテストします。

于 2012-10-22T09:33:01.497 に答える
1

私の意見では、UIImageViewと同じサイズの非表示のUIViewを描画用に取得し、UIViewにtouchメソッドを実装して描画するのが最善の方法だと思います。

次のようなものを使用できます:

CGPoint temp=[touch locationInView:self];

次のような方法でこれを使用します。

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

すべてのポイントを配列に格納してから、それらのポイントをそのままUIImageViewに描画します。

于 2012-10-22T09:58:22.133 に答える
0

MuhammadSaadAnsariを参照してください

Swiftを使用

func drawLines ( originalImage:UIImage, lineColor:CGColor ) -> UIImage{

UIGraphicsBeginImageContextWithOptions(originalImage.size,false,0.0)

originalImage.drawInRect(CGRectMake( 0, 0, originalImage.size.width, originalImage.size.height ))

let context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 5.0);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, originalImage.size.width, 0);
CGContextSetStrokeColorWithColor(context,lineColor);
CGContextStrokePath(context);

// Create new image
var newImage = UIGraphicsGetImageFromCurrentImageContext();

// Tidy up
UIGraphicsEndImageContext();

return newImage

}

于 2015-03-19T07:33:19.533 に答える