| destX = dr + (i - cx) *cos(radian) - (j - cy)*sin(radian); destY = dr + (j - cy) *cos(radian) + (i - cx)*sin(radian); |
![]() 图三 旋转算法示意图 |
![]() 图四 算法流程图 |
| /** *@param imgSource 源图像 *@param cx 旋转点相对于源图像坐上角横坐标 *@param cy 旋转点相对于源图像坐上角纵坐标 *@param theta 图像逆时针旋转的角度 *@param dd 含2个元素的整形数组,存放新图像相对源图像沿x轴和y轴的位置偏移量 *@return 旋转后的图像 **/ public Image rotate(Image imgSource, int cx, int cy, double theta, int[] dd) { if (Math.abs(theta % 360) < 0.1) return imgSource; //角度很小时直接返回 int w1 = imgSource.getWidth(); //原始图像的高度和宽度 int h1 = imgSource.getHeight(); int[] srcMap = new int[w1 * h1]; imgSource.getRGB(srcMap, 0, w1, 0, 0, w1, h1); //获取原始图像的像素信息 int dx = cx > w1 / 2 ? cx : w1 - cx; //计算旋转半径 int dy = cy > h1 / 2 ? cy : h1 - cy; double dr = Math.sqrt(dx * dx + dy * dy); int wh2 = (int) (2 * dr + 1); //旋转后新图像为正方形,其边长+1是为了防止数组越界 int[] destMap = new int[wh2 * wh2]; //存放新图像象素的数组 double destX, destY; double radian = theta * Math.PI / 180; //计算角度计算对应的弧度值 for (int i = 0; i < w1; i++) { for (int j = 0; j < h1; j++) { if (srcMap[j * w1 + i] >> 24 != 0) { //对非透明点才进行处理 // 得到当前点经旋转后相对于新图像左上角的坐标 destX = dr + (i - cx) * Math.cos(radian) + (j - cy)* Math.sin(radian); destY = dr + (j - cy) * Math.cos(radian) - (i - cx)* Math.sin(radian); //从源图像中往新图像中填充像素 destMap[(int) destY * wh2 + (int) destX] = srcMap[j * w1 + i]; } } } dd[0] = cx-dr; //返回位置偏移分量 dd[1] = cy-dr; return Image.createRGBImage(destMap, wh2, wh2, true); //返回旋转后的图像 } |
关注此文的读者还看过: