How to create a UITextView with a three-dimensional shadow border?

In another post, luvieere shared a way in which rounded corners can be applied to a text representation using the QuartzCore framework ( see post ). It seems to me that a three-dimensional border similar to that found on a UITextField can be created through layers instead of using a background image.

Does anyone know if and how to do this? I would really like to find a way to add a 3D frame WITHOUT having to start a graphical editor and create a three-dimensional shaded background. Thank!

+3
source share
2 answers

In the view controller:

    newCommentBody.layer.cornerRadius = 7;  
    newCommentBody.clipsToBounds = YES;  

Make a new TextView class inherit from UITextView

#import "TextView.h"
#import <CoreGraphics/CoreGraphics.h>
#import <CoreGraphics/CGColor.h>

@implementation TextView

-(void) drawRect:(CGRect)rect {
    UIGraphicsBeginImageContext(self.frame.size);

    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(currentContext, 1.0); //or whatever width you want
    CGContextSetRGBStrokeColor(currentContext, 0.6, 0.6, .6, 1.0);

    CGRect myRect = CGContextGetClipBoundingBox(currentContext);  
    //printf("rect = %f,%f,%f,%f\n", myRect.origin.x, myRect.origin.y, myRect.size.width, myRect.size.height);

    float myShadowColorValues[] = {0,0,0,1};
    CGColorSpaceRef myColorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorRef = CGColorCreate(myColorSpace, myShadowColorValues);
    CGContextSetShadowWithColor(currentContext, CGSizeMake(0, -1), 3, colorRef);
    // CGContextSetShadow(currentContext, CGSizeMake(0, -1), 3);

    CGContextStrokeRect(currentContext, myRect);
    UIImage *backgroundImage = (UIImage *)UIGraphicsGetImageFromCurrentImageContext();
    UIImageView *myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    [myImageView setImage:backgroundImage];
    [self addSubview:myImageView];
    [backgroundImage release];  

    UIGraphicsEndImageContext();
}

@end
+4
source
m_txtViewSource.layer.borderWidth = 1;

m_txtViewSource.layer.borderColor = [[UIColor grayColor] CGColor];

it's not 3D, but simple and safe code

+1
source

Source: https://habr.com/ru/post/1727098/


All Articles