Stretching a image in iOS using colorWithPatternIm

2019-05-30 09:46发布

I have a image like this: enter image description here. In iPad, when I place it with these code:

[separatorLineView setFrame:CGRectMake(10, 0, 430, 3)];
separatorLineView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"divider.png"]];

In iPad, it shows up like this:

enter image description here

In iPhone, it works fine.

The code for iPhone looks like this:

[separatorLineView setFrame:CGRectMake(10, 0, 180, 3)];
    separatorLineView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"divider.png"]];

How to avoid the repetition? Must I use resizableImageWithCapInsets?

Need some guidance and suggestions..

2条回答
放荡不羁爱自由
2楼-- · 2019-05-30 10:28

add the following method

-(UIImage *)imageResize :(UIImage*)img andResizeTo:(CGSize)newSize
{
    CGFloat scale = [[UIScreen mainScreen]scale];

    //UIGraphicsBeginImageContext(newSize);
    UIGraphicsBeginImageContextWithOptions(newSize, NO, scale);
    [img drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

now change your code as

[separatorLineView setFrame:CGRectMake(10, 0, 180, 3)];
    separatorLineView.backgroundColor = [UIColor colorWithPatternImage:[self imageResize :[UIImage imageNamed:@"divider.png"] andResizeTo:separatorLineView.frame.size]];
查看更多
贼婆χ
3楼-- · 2019-05-30 10:36
登录 后发表回答