Q5.8 DrawHorizontalLine

Q: A monochrome screen is stored as a singal array of bytes, allowing eight consecutive pixels to be stored in one byte. The screen has width w, where w is a divisible by 8 (that is, no byte will be split across rows). The height of the screen , of course, can be derived from the length of the array and the width. Implement a functin drawHorizontalLine(byte[] screen, int width, int x1, int x2, int y) which draws a horizontal line from (x1, y) to (x2, y).

A:

思路1: 逐像素置1即可。

思路2:逐字节置1。 注意一下边界情况的处理。

#include <iostream>
using namespace std;
 
typedef unsigned char BYTE;

void drawLine(BYTE screen[], int width, int x1, int x2, int y) {
	int start_offset = x1%8;
	int first_full_byte = x1/8;
	if (start_offset != 0) {
		first_full_byte++;
	}
	int end_offset = x2%8;
	int end_full_byte = x2/8;
	if (end_offset != 7) {
		end_full_byte--;
	}
	
	for (int i = first_full_byte; i <= end_full_byte; i++) {
		screen[(width/8)*y+i] = (BYTE) 0xFF;
	}
	
	BYTE start_mask = (BYTE) (0xFF>>start_offset);
	BYTE end_mask = (BYTE) ~(0xFF>>(end_offset+1));
	if ((x1/8) == (x2/8)) {
		BYTE mask =(BYTE) start_mask&end_mask;
		screen[(width/8)*y+x1/8] |= mask;
	} else {
		if (start_offset != 0) {
			int ind = (width/8)*y + first_full_byte - 1;
			screen[ind] |= start_mask;
		}
		if (end_offset != 7) {
			int ind = (width/8)*y + end_full_byte + 1;
			screen[ind] |= end_mask;
		}
		
	}
	
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值