【发布时间】:2016-09-27 09:38:54
【问题描述】:
【问题讨论】:
-
你需要在 Objective C 或 swift 中
-
我需要快速代码@Anbu.Karthik
标签: ios swift uiimageview swift3
【问题讨论】:
标签: ios swift uiimageview swift3
您可以从其中包含图像的 imageView 框架或图像自身获取此信息。既然你还没有说你是否使用 imageView ,这里是两者:
从 imageView 获取大小和坐标:
let x:CGFloat = imageView.frame.origin.x
let y:CGFloat = imageView.frame.origin.y
let width:CGFloat = imageView.frame.size.width
let height:CGFloat = imageView.frame.size.height
从 UIImage 获取尺寸(没有坐标):
let width:CGFloat = image.size.width
let height:CGFloat = image.size.height
【讨论】:
从图像中读取像素,并在从图像中获取CGRect 后与您的设备宽度和高度进行比较。
- (CGRect)getRectFromImage:(UIImage*)image
{
// First get the image into your data buffer
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
int x = 0;
int y = 0;
int xPos = 0;
int yPos = 0;
int xMax = 0;
int yMax = 0;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
unsigned char alphaByte = rawData[(y*bytesPerRow)+(x*bytesPerPixel)+3];
if (alphaByte > 0) {
if (xPos == 0) {
xPos = x;
}
if (yPos == 0) {
yPos = y;
}
if (x < xPos) {
xPos = x;
}
if (y < yPos) {
yPos = y;
}
if (x > xMax) {
xMax = x;
}
if (y > yMax) {
yMax = y;
}
}
}
}
NSLog(@"(%i,%i,%i,%i)", xPos, yPos,xMax-xPos,yMax-yPos);
free(rawData);
return CGRectMake(xPos, yPos, xMax-xPos, yMax-yPos);
}
【讨论】:
Swift 3 Xcode 8 。
它仅适用于viewDidAppear 函数
@IBOutlet var myImage: UIImageView!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let Height = myImage.frame.height
let Width = myImage.frame.width
let xPosition = myImage.frame.minX
let yPosition = myImage.frame.minY
print("Height: \(Height), width: \(Width), xPosition: \(xPosition), yPosition: \(yPosition)")
}
【讨论】: