itsource

UIView에서 선 그리기

mycopycode 2023. 8. 30. 21:42
반응형

UIView에서 선 그리기

UI 뷰에서 수평선을 그려야 합니다.그것을 하는 가장 쉬운 방법은 무엇입니까?예를 들어 y-cord=200에서 검은색 가로선을 그립니다.

인터페이스 작성기를 사용하지 않습니다.

조금 늦었을 수도 있지만, 더 좋은 방법이 있다는 것을 덧붙이고 싶습니다.UIView를 사용하는 것은 간단하지만 상대적으로 느립니다.이 방법은 뷰가 자동으로 그리는 방식을 재정의하고 더 빠릅니다.

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);

    // Draw them with a 2.0 stroke width so they are a bit more visible.
    CGContextSetLineWidth(context, 2.0f);

    CGContextMoveToPoint(context, 0.0f, 0.0f); //start at this point

    CGContextAddLineToPoint(context, 20.0f, 20.0f); //draw to this point

    // and now draw the Path!
    CGContextStrokePath(context);
}

사용자의 경우(수평선)에서 가장 쉬운 방법은 검은색 배경색과 프레임으로 하위 보기를 추가하는 것입니다.[0, 200, 320, 1].

코드 샘플 (오류가 없었으면 좋겠어요 - Xcode 없이 작성했습니다):

UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, 1)];
lineView.backgroundColor = [UIColor blackColor];
[self.view addSubview:lineView];
[lineView release];
// You might also keep a reference to this view 
// if you are about to change its coordinates.
// Just create a member and a property for this...

다른 방법은 drawRect 메서드에서 선을 그리는 클래스를 만드는 것입니다(여기서 내 코드 샘플을 볼 수 있습니다).

스위프트 3와 스위프트 4

이것이 당신이 당신의 뷰의 끝에 회색 선을 그릴 수 있는 방법입니다(b123400의 답변과 같은 생각입니다).

class CustomView: UIView {

    override func draw(_ rect: CGRect) {
        super.draw(rect)
        
        if let context = UIGraphicsGetCurrentContext() {
            context.setStrokeColor(UIColor.gray.cgColor)
            context.setLineWidth(1)
            context.move(to: CGPoint(x: 0, y: bounds.height))
            context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
            context.strokePath()
        }
    }
}

텍스트가 없고 배경색이 있는 레이블을 추가하기만 하면 됩니다.선택한 좌표와 높이 및 너비를 설정합니다.수동으로 또는 인터페이스 작성기를 사용하여 이 작업을 수행할 수 있습니다.

다음에 대해 UIBizerPath 클래스를 사용할 수 있습니다.

원하는 만큼 선을 그릴 수 있습니다.

하위 분류 UIView:

    @interface MyLineDrawingView()
    {
       NSMutableArray *pathArray;
       NSMutableDictionary *dict_path;
       CGPoint startPoint, endPoint;
    }

       @property (nonatomic,retain)   UIBezierPath *myPath;
    @end

그리고 pathArray와 dict를 초기화했습니다.선 그리기에 사용될 경로 객체.저는 제 프로젝트에서 코드의 주요 부분을 작성하고 있습니다.

- (void)drawRect:(CGRect)rect
{

    for(NSDictionary *_pathDict in pathArray)
    {
        [((UIColor *)[_pathDict valueForKey:@"color"]) setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
        [[_pathDict valueForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
    }

    [[dict_path objectForKey:@"color"] setStroke]; // this method will choose the color from the receiver color object (in this case this object is :strokeColor)
    [[dict_path objectForKey:@"path"] strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];

}

터치Begin 메서드:

UITouch *touch = [touches anyObject];
startPoint = [touch locationInView:self];
myPath=[[UIBezierPath alloc]init];
myPath.lineWidth = currentSliderValue*2;
dict_path = [[NSMutableDictionary alloc] init];

이동된 메서드를 누릅니다.

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

 [myPath removeAllPoints];
        [dict_path removeAllObjects];// remove prev object in dict (this dict is used for current drawing, All past drawings are managed by pathArry)

    // actual drawing
    [myPath moveToPoint:startPoint];
    [myPath addLineToPoint:endPoint];

    [dict_path setValue:myPath forKey:@"path"];
    [dict_path setValue:strokeColor forKey:@"color"];

    //                NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
    //                [pathArray addObject:tempDict];
    //                [dict_path removeAllObjects];
    [self setNeedsDisplay];

touchs Ended로 터치엔드 메서드:

        NSDictionary *tempDict = [NSDictionary dictionaryWithDictionary:dict_path];
        [pathArray addObject:tempDict];
        [dict_path removeAllObjects];
        [self setNeedsDisplay];

하나의 다른 가능성(그리고 더 짧은 가능성).만약 당신이 안에 있다면, 다음과 같은 것이 옳습니다.

[[UIColor blackColor] setFill];
UIRectFill((CGRect){0,200,rect.size.width,1});

스위프트 3, 4, 5

이게 제가 찾을 수 있는 가장 단순한...

let lineView = UIView(frame: CGRect(x: 4, y: 50, width: self.view.frame.width, height: 1))
lineView.backgroundColor = .lightGray
self.view.addSubview(lineView)

가이 다허의 대답을 토대로.

GetCurrentContext()가 0을 반환하면 응용 프로그램이 손상될 수 있으므로 ?를 사용하지 않도록 합니다.

만약 다음과 같은 진술이 나온다면 나는 nill check를 할 것입니다.

class CustomView: UIView 
{    
    override func draw(_ rect: CGRect) 
    {
        super.draw(rect)
        if let context = UIGraphicsGetCurrentContext()
        {
            context.setStrokeColor(UIColor.gray.cgColor)
            context.setLineWidth(1)
            context.move(to: CGPoint(x: 0, y: bounds.height))
            context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
            context.strokePath()
        }
    }
}

텍스트 없이 배경색으로 레이블을 추가합니다(예: 높이=1).코드를 통해 또는 인터페이스 빌더에서 수행합니다.

언급URL : https://stackoverflow.com/questions/3128752/draw-line-in-uiview

반응형