java graphics 像素,使用Graphics2D以亚像素级精度绘制图像

I am currently attempting to draw images on the screen at a regular rate like in a video game.

Unfortunately, because of the rate at which the image is moving, some frames are identical because the image has not yet moved a full pixel.

Is there a way to provide float values to Graphics2D for on-screen position to draw the image, rather than int values?

Initially here is what I had done:

BufferedImage srcImage = sprite.getImage ( );

Position imagePosition = ... ; //Defined elsewhere

g.drawImage ( srcImage, (int) imagePosition.getX(), (int) imagePosition.getY() );

This of course thresholds, so the picture doesn't move between pixels, but skips from one to the next.

The next method was to set the paint color to a texture instead and draw at a specified position. Unfortunately, this produced incorrect results that showed tiling rather than correct antialiasing.

g.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );

BufferedImage srcImage = sprite.getImage ( );

g.setPaint ( new TexturePaint ( srcImage, new Rectangle2D.Float ( 0, 0, srcImage.getWidth ( ), srcImage.getHeight ( ) ) ) );

AffineTransform xform = new AffineTransform ( );

xform.setToIdentity ( );

xform.translate ( onScreenPos.getX ( ), onScreenPos.getY ( ) );

g.transform ( xform );

g.fillRect(0, 0, srcImage.getWidth(), srcImage.getHeight());

What should I do to achieve the desired effect of subpixel rendering of an Image in Java?

解决方案

You can use a BufferedImage and AffineTransform, draw to the buffered image, then draw the buffered image to the component in the paint event.

/* overrides the paint method */

@Override

public void paint(Graphics g) {

/* clear scene buffer */

g2d.clearRect(0, 0, (int)width, (int)height);

/* draw ball image to the memory image with transformed x/y double values */

AffineTransform t = new AffineTransform();

t.translate(ball.x, ball.y); // x/y set here, ball.x/y = double, ie: 10.33

t.scale(1, 1); // scale = 1

g2d.drawImage(image, t, null);

// draw the scene (double percision image) to the ui component

g.drawImage(scene, 0, 0, this);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值