How do I make the lineWidth of UIBezierPath always be 1 under transform change

46 views Asked by At

I have a UIView, and on the view I add a UIBezierPath drawing, and when I make a CGAffineTransformScale on UIView, I will trigger (setNeeds trigger redraw) after I have done the scaling changes. Scaling to scale doesn't have any problems, but when I scale to a different width to a different height, the drawn line width is wrong. For example, when my width scaling ratio (sy) is greater than the height scaling ratio (sx), the drawn graph will always have a width line width several times larger than the height. And the other way around, how do I set it so that I always draw a line width of 1? Like pic, The bottom triangle is my prototype, and I want it to have a width of 1 no matter how I scale it, right。 If anyone can help me, I would be very grateful!

-(void)test111
{
    MyView *testView = [[MyView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [self.view addSubview:testView];
    
    UIBezierPath *myPath = [UIBezierPath bezierPath];
    self.bezierPath = myPath;
    CAShapeLayer *myLayer = [CAShapeLayer layer];
    self.shaperLayer = myLayer;
    myLayer.strokeColor = [UIColor blackColor].CGColor;
    myLayer.fillColor = [UIColor clearColor].CGColor;
    myLayer.lineWidth = line_width;
    myLayer.allowsEdgeAntialiasing = YES;
    myLayer.contentsScale = [UIScreen mainScreen].scale;
    [testView.layer addSublayer:triangleLayer];
    
    testView.transform = CGAffineTransformScale(testView.transform, 2, 0.5);
    [testView setNeedsDisplay];
}

#pragma mark - my view drawRect
- (void)drawRect:(CGRect)rect
{
    UIBezierPath *path = self.bezierPath;
    CGFloat a = self.transform.a;
    CGFloat b = self.transform.b;
    CGFloat c = self.transform.c;
    CGFloat d = self.transform.d;
    
    CGFloat xScale = 1.0 / sqrt(a * a + c * c);
    CGFloat yScale = 1.0 / sqrt(b * b + d * d);
    CGFloat lineWidth = sqrt(xScale * xScale + yScale * yScale);
    self.shaperLayer.lineWidth = lineWidth;
    self.shaperLayer.path = path.CGPath;
    self.shaperLayer.path = path.CGPath;
}
0

There are 0 answers