Графика Java. При рисовании нескольких изображений рядом друг с другом создаются пустые строки | РЕШЕНОJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Графика Java. При рисовании нескольких изображений рядом друг с другом создаются пустые строки | РЕШЕНО

Сообщение Anonymous »

Я пытаюсь нарисовать карту своей игры, у нее есть объект tiles с координатами x и y.
Изображение плиток хранится в 1 классе, и я изменяю их размер, как только заканчиваю масштабирование.
/>Я хочу рисовать изображения с двойной точностью, на самом деле я использую AffineTransform для их перевода, а также масштабирую с двойной точностью.
В Класс Camera. У меня переменная масштабирования имеет значение double.
Когда масштаб равен 0, кажется, что все в порядке, но когда я перемещаю мышь, эта ошибка все еще случается. (Поскольку камера перемещается в зависимости от расстояния мыши от центра)
Я рисую все на панели под названием GameScreen, у меня есть несколько Классы ScreenPainter, в которых я рисую разные объекты, а затем рисую все на этой панели.
Класс GameScreen:

Код: Выделить всё

public class GameScreen extends JPanel {

private static GameScreen INSTANCE;
private static Graphics2D graphics2D;

private List painters = new ArrayList();

public GameScreen() {
INSTANCE = this;
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
graphics2D = (Graphics2D) g;
graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

for (ScreenPainter painter : painters) painter.paint();
for (BAText text : new ArrayList(TextRegistry.getTexts().values())) {
if (text != null) text.drawText(graphics2D);
}

//if (BlueArchangels.STATE == GameState.PAUSE) MenuRegistry.getExitMenu().paint(graphics);

graphics2D.dispose();
}

public void updatePainters() {
painters = new ArrayList(ScreenPainterManager.getPainters());
}

public static GameScreen INSTANCE() {
return INSTANCE;
}

public static Graphics2D getGraphics2D() {
return graphics2D;
}
}
Метод в классе MapPainter

Код: Выделить всё

    @Override
public void paint() {
if (grids == null) {
assignValue();
return;
}

double cellWidth = getCellWidth(), cellHeight = getCellHeight();
boolean zooming = Camera.zooming();

for (Map.TileGrid tileGrid : grids) {
int offsetX = tileGrid.getOffsetX(), offsetY = tileGrid.getOffsetY();

for (Map.Tile tile : tileGrid.getAllTiles()) {
BufferedImage image = tile.getTileImage();
if (image == null) continue;

double width = cellWidth, height = cellHeight;
double x = width * (tile.x + offsetX), y = height * (-tile.y - offsetY);

AffineTransform transform = new AffineTransform();

// Ground tiles are already at the same size as the cell.
if (!tile.isGround()) {
double w = image.getWidth(), h = image.getHeight();
// Check how many times the cell stays inside the image, to scale it later.
double timesX = w / width, timesY = h / height;

// Calculate the target size of the tile.
width = width * timesX;
height = height * timesY;

// Scale the size to the target size.
transform.scale(width / w, height / h);

// Now with the target size, we calculate the exact location to place it in its cell at (x;  y).
// Otherwise, when scaled it will be placed on another cell and not its original.

// Now we correct the position by placing the x coordinate and
// the bottom part of the tile in the middle of the cell.
x += -(width / 2D) + (cellWidth / 2D);
y += -height + (cellHeight / 2D);
}

if (Camera.isOutCamera(x, y, width, height)) continue;

if (zooming) {
// If zooming and the tile is ground, scale it to the correct size while waiting for resizing.
if (tile.isGround()) {
//transform.scale(width / image.getWidth(), height / image.getHeight());
x += -(width / 2) + (cellWidth / 2);
y += -(height / 2) + (cellHeight / 2);
}
wasZooming = true;
} else {
// Once the game is no more zooming, update the ground tile sizes and draw them without scaling.
if (wasZooming) resizeMapTiles();
wasZooming = false;
}
transform.translate(Camera.toX(x), Camera.toY(y));

if (zooming) {
// If zooming and the tile is ground, scale it to the correct size while waiting for resizing.
if (tile.isGround()) transform.scale(width / image.getWidth(), height / image.getHeight());

}

int degrees = tile.getRotation();
if (degrees != 0) transform.rotate(Math.toRadians(degrees), width / 2D, height / 2D);

ScreenPainter.drawImage(image, transform);
}
}
}

Есть идеи, почему это происходит? Видео проблемы
Редактировать 1
Я нашел основную проблему этих строк. (Из того, что я тестировал)
Проблема заключается в рисовании с двойной точностью, я отредактировал переменную масштабирования, сделав ее целой, и теперь проблема значительно уменьшилась. проблема возникает, когда я пытаюсь переместить, потому что местоположение также имеет двойную точность, когда я рисую с целочисленной позицией, проблема не проявляется.
Теперь другой вопрос: как решить проблему двойной точности? Это проблема рендеринга? Проблема с округлением? Кто-нибудь когда-нибудь сталкивался с этим?

Подробнее здесь: https://stackoverflow.com/questions/792 ... mpty-lines
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»